Swift - 基于比较两个数组值的结果的新数组

时间:2022-02-28 08:17:46
idsArr = [ "id12345", "id27891", "id98654"]
idsNameIntvalueArr = [["id22913", "Peter Parker", 15], ["id12345", "Donald Duck", 6], ["id98654", "Mickey Mouse", 9], ["id112233", "Lion King", 9]]

I'm new in Swift, please give me advice, what is the best practice to compare this 2 arrays by id, if id matches, need to make new array with "name" and Int value, in this case:

我是Swift的新手,请给我建议,用ID比较这2个数组的最佳做法是什么,如果id匹配,需要用“name”和Int值创建新数组,在这种情况下:

resultArr = [["Donald Duck", 6],["Mickey Mouse", 9]]

Thanks.

谢谢。

1 个解决方案

#1


1  

You can do that like this:

你可以这样做:

let resultArr = idsNameIntvalueArr.filter({ idsArr.contains($0[0] as! String) }).map({ [$0[1], $0[2]] })

First, you need to filter the array to include only the members whose IDs exists in idsArr.

首先,您需要过滤数组以仅包含其ID存在于idsArr中的成员。

Then, after filtering the array you need to create sub-arrays that contains only the name and age, and this is what map does.

然后,在过滤数组之后,您需要创建仅包含名称和年龄的子数组,这就是地图的作用。

#1


1  

You can do that like this:

你可以这样做:

let resultArr = idsNameIntvalueArr.filter({ idsArr.contains($0[0] as! String) }).map({ [$0[1], $0[2]] })

First, you need to filter the array to include only the members whose IDs exists in idsArr.

首先,您需要过滤数组以仅包含其ID存在于idsArr中的成员。

Then, after filtering the array you need to create sub-arrays that contains only the name and age, and this is what map does.

然后,在过滤数组之后,您需要创建仅包含名称和年龄的子数组,这就是地图的作用。