0

在我的项目中,我有两个 NSArray 并且两个数组都包含两个值频率和键。现在我必须将这两个 NSArray 与键的引用进行比较,然后我必须找到公共键,并从这个公共键中我必须将每个数组的频率存储在另一个数组中,以便我对每个数组都有共同的计数

例子

Printing description of xSeriesArray:

{
  frequency = 60;
  key = 5591090;
},
{
  frequency = 50;
  key = 5591089;
},
{
  frequency = 40;
  key = 5591082;
},
{
 frequency = 30;
 key = 5591078;
},
{
 frequency = 20;
 key = 5591077;
},
{
 frequency = 10;
 key = 5591076;
}


Printing description of ySeriesArray:
<__NSArrayM 0xa1e1270>
  {
   frequency = 500;
   key = 5591089;
  },
  {
   frequency = 400;
   key = 5591082;
 },
 {
  frequency = 300;
  key = 5591078;
  },
 {
  frequency = 200;
  key = 5591077;
 },
 {
  frequency = 100;
  key = 5591076;
 }

在第一个数组中的上述数组数据上我有 6 个计数,在另一个我有 5 个计数请帮助我从这两个 NSArray 中找到公共键

4

1 回答 1

4

使用 Set 这是查找共同值的最简单方法。

NSMutableSet* set1 = [NSMutableSet setWithArray:yourFirstArray];
NSMutableSet* set2 = [NSMutableSet setWithArray:yourSecondArray];
[set1 intersectSet:set2]; //this will give you only the obejcts that are in both sets

NSArray* result = [set1 allObjects];

检查 Swift 代码:-

var set1 = Set<AnyHashable>(yourFirstArray)
var set2 = Set<AnyHashable>(yourSecondArray)
set1.intersect(set2) //this will give you only the obejcts that are in both sets

let result = Array(set1)
于 2013-10-15T06:48:15.157 回答