2013-03-15 3 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

이의 누구 IDS 모든 배열에 표시되는 객체가 "유비쿼터스"있다고 가정 해 봅시다 (일 네이밍 = P 어렵다) : 중첩 된 for 루프 조금 못생긴

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}] 

하지만, 이것은 어딘가에 망쳐 놓지 않는 한 O (n) (n은 객체의 총 수)가되어야합니다.

업데이트 : 당신은 또한 수행 할 수 있습니다 대신 비밀 [].concat (arr for id, arr of objectsById when arr.length is arrays.length)... 라인의

res = [] 
for id, arr of objectsById when arr.length is arrays.length 
    res = res.concat arr 
res 

. 그것은 틀림없이 더 읽기 쉽고 saner JS를 생성합니다 :)

관련 문제