Coffeescript 基于对象特性值的对象数组相交

Coffeescript 基于对象特性值的对象数组相交,coffeescript,underscore.js,Coffeescript,Underscore.js,如何获得只包含id属性值存在且在所有数组中相同的对象的结果数组?即: array1 = [ { id: "a", score: 1 }, { id: "b", score: 3 }, { id: "c", score: 8 }] array2 = [ { id: "a", score: 2 }, { id: "z", score: 5 }, { id: "c", score: 1 }] array3 = [ { id: "a", score: 3 }, { id: "f", score: 2 }

如何获得只包含id属性值存在且在所有数组中相同的对象的结果数组?即:

array1 = [ { id: "a", score: 1 }, { id: "b", score: 3 }, { id: "c", score: 8 }]
array2 = [ { id: "a", score: 2 }, { id: "z", score: 5 }, { id: "c", score: 1 }]
array3 = [ { id: "a", score: 3 }, { id: "f", score: 2 }, { id: "c", score: 2 }]

假设ID出现在每个数组中的对象“无处不在”(命名对象为hard=p):

嵌套的
for
循环有点难看,但这应该是O(n)(n是对象的总数),除非我搞砸了

更新:您还可以执行以下操作:

filterUbiquitousObjects = (arrays...) ->
  objectsById = {}
  (objectsById[obj.id] or= []).push obj for obj in arr for arr in arrays 
  [].concat (arr for id, arr of objectsById when arr.length is arrays.length)...

array1 = [{ id: "a", score: 1 }, { id: "b", score: 3 }, { id: "c", score: 8 }]
array2 = [{ id: "a", score: 2 }, { id: "z", score: 5 }, { id: "c", score: 1 }]
array3 = [{ id: "a", score: 3 }, { id: "f", score: 2 }, { id: "c", score: 2 }]

console.log filterUbiquitousObjects array1, array2, array3
# Output:
# [{id:"a", score:1}, {id:"a", score:2}, {id:"a", score:3}, {id:"c", score:8}, 
# {id:"c", score:1}, {id:"c", score:2}]
而不是神秘的
[].concat(arr代表id,arr.length为arrays.length时objectsById的arr).
行。它可以说更具可读性,并将生成更理智的JS:)

filterUbiquitousObjects = (arrays...) ->
  objectsById = {}
  (objectsById[obj.id] or= []).push obj for obj in arr for arr in arrays 
  [].concat (arr for id, arr of objectsById when arr.length is arrays.length)...

array1 = [{ id: "a", score: 1 }, { id: "b", score: 3 }, { id: "c", score: 8 }]
array2 = [{ id: "a", score: 2 }, { id: "z", score: 5 }, { id: "c", score: 1 }]
array3 = [{ id: "a", score: 3 }, { id: "f", score: 2 }, { id: "c", score: 2 }]

console.log filterUbiquitousObjects array1, array2, array3
# Output:
# [{id:"a", score:1}, {id:"a", score:2}, {id:"a", score:3}, {id:"c", score:8}, 
# {id:"c", score:1}, {id:"c", score:2}]
res = []
for id, arr of objectsById when arr.length is arrays.length
  res = res.concat arr
res