首页 > 解决方案 > Swift - 基于另一个称为查询的数组有效地查询一个整数数组,该数组具有第一个数组的索引

问题描述

我想根据另一个称为查询的数组有效地查询一个整数数组,该数组具有第一个数组的索引。

let arrayWithData = [10, 20, 30, 15, 25, 35, 56]
let queries = [2, 4, 6]

新数组应返回:

let queriedArray = [30, 25, 56]

解释:

30 是 arrayWithData 的索引 2

25 是 arrayWithData 的索引 4

56 是 arrayWithData 的索引 6

如何在不使用循环的情况下快速有效地实现这一点。也许使用地图或过滤器

标签: arraysswiftfilter

解决方案


你可以试试

let res = queries.compactMap { $0 < arrayWithData.count ?  arrayWithData[$0] : nil  }

如果您 100% 确定查询索引将在数组计数中使用

let res = queries.map{ arrayWithData[$0]}

推荐阅读