在对象数组中查找交集

时间:2019-03-03 17:55:43

标签: javascript

假设我有以下包含对象(歌曲)数组的数组:

request.setValue("Bearer base64EncodedString", forHTTPHeaderField: "Authorization")

我希望遍历数据并返回在每个数组中找到的对象,因此在这种情况下,返回值将是:

[
  [
    {
      name: 'I Want You Back',
      id: 1
    },
    {
      name: 'ABC',
      id: 2
    }
  ],
  [
    {
      name: 'I Want You Back',
      id: 1
    },
    {
      name: 'Dont Stop Me Now',
      id: 3
    }
  ],
  [
    {
      name: 'I Want You Back',
      id: 1
    },
    {
      name: 'ABC',
      id: 2
    }
  ],
]

到目前为止,我只设法对字符串数组(而不是对象)进行处理,就像这样:

{
   name: 'I Want You Back',
   id: 1
}

我一直在尝试,但是我无法对我的对象(例如,它们的名称或ID)应用相同的逻辑。如果你们中的一些向我展示了您将如何做,我将非常感谢。

1 个答案:

答案 0 :(得分:1)

您可以按唯一的id来计数对象,然后遍历并找到其计数与数组长度相同的对象:

const songs = [[{name: 'I Want You Back',id: 1},{name: 'ABC',id: 2}],[{name: 'I Want You Back',id: 1},{name: 'Dont Stop Me Now',id: 3}],[{name: 'I Want You Back',id: 1},{name: 'ABC',id: 2}],]

// count of each unique id
let counts  = songs.reduce((count, arr) => {
  arr.forEach(obj => {
    if (!count[obj.id]) count[obj.id] = {obj, count: 0}
    count[obj.id].count += 1  
  })
  return count
}, {})

// now filter out all whose count isn't the length
// and map to retreive just the object
let intersect = Object.values(counts)
                .filter(o => o.count == songs.length)
                .map(o => o.obj)

console.log(intersect)

如果通过值对对象相等性进行测试,这当然会容易得多,但是由于不是那样,您需要跳过一些额外的步骤。