【问题标题】:How to find common value from two NSArray? [duplicate]如何从两个 NSArray 中找到共同值? [复制]
【发布时间】:2013-10-15 06:41:46
【问题描述】:

在我的项目中,我有两个 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 中找到公共密钥

【问题讨论】:

    标签: ios count nsarray


    【解决方案1】:

    Used 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)
    

    【讨论】:

    • 现在我得到了公共密钥,但是如何从这些公共密钥中找到频率?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多