2013-03-15 108 views
2
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属性值且存在且所有数组都相同的对象的结果数组?即:基于对象属性值的对象数组的交集

resultyArray = [ 
    { id: "a", score: 1 }, 
    { id: "a", score: 2 }, 
    { id: "a", score: 3 }, 
    { id: "c", score: 8 }, 
    { id: "c", score: 1 }, 
    { id: "c", score: 2 } 
] 

回答

1

假设其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 :)