假设其 id 出现在每个数组上的对象是“无处不在的”(命名很难 =P):
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}]
嵌套for
循环有点难看,但这应该是 O(n) (作为 n 对象的总数),除非我在某个地方搞砸了。
更新:你也可以这样做:
res = []
for id, arr of objectsById when arr.length is arrays.length
res = res.concat arr
res
而不是神秘的[].concat (arr for id, arr of objectsById when arr.length is arrays.length)...
线。可以说它更具可读性并且会生成更理智的 JS :)