2017-06-15 72 views
2

我有一個包含對象數組的數組:傳遞一個數組的數組到lodash路口

let data = [[{a:0}, {b:1}], [{a:1}, {b:1}]] 

現在,我想使這兩個數組的lodash intersection,返回[{b:1}]

當我做這:

import {intersection} from 'lodash' 

return intersection([{a:0}, {b:1}], [{a:1}, {b:1}]) 

結果是正確的。

但是當我做

return intersection(data) 

我只是得到了相同的結果了。

是否有一種簡單的方法可以將所有數據從數據傳遞到相交函數?我最初的想法是使用.map,但這返回另一個數組...

+0

我不認爲你會從中得到任何回報,因爲我相信它是比較引用而不是值。您應該使用['intersectionBy'](https://lodash.com/docs/4.17.4#intersectionBy)或['intersectionWith'](https://lodash.com/docs/4.17.4#intersectionWith)。 – mhodges

回答

6

你可以只是spread的數組。

intersection(...arrayOfarrays); 

或者,在預ES6環境中,使用apply

intersection.apply(null, arrayOfArrays); 

或者,你可以intersect轉換成函數展開的爭論:

const intersectionArrayOfArrays = _.spread(_.intersection); 
intersectionArrayOfArrays(arrayOfArrays); 

請注意,雖然在lodash doesn't automatically work on arrays of objects交叉點。

你可以使用intersectionBy,如果你想相交的財產b

const arrayOfArrays = [[{a:0}, {b:1}], [{a:1}, {b:1}]]; 
 
console.log(
 
    _.intersectionBy(...arrayOfArrays, 'b') 
 
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

intersectionWith,如果你想相交通過引用或深比較相同的對象:

const a1 = {a: 0}; 
 
const a2 = {a: 1}; 
 
const b = {b: 1}; 
 
const arrayOfArrays = [[a1, b], [a2, b]]; 
 

 
// reference comparison 
 
console.log(
 
    _.intersectionWith(...arrayOfArrays, (a, b) => a === b) 
 
) 
 

 
// deep equality comparison 
 
console.log(
 
    _.intersectionWith(...arrayOfArrays, _.isEqual) 
 
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

+0

不知道你可以傳播數組。謝謝:) –

+0

@MihaŠušteršič很樂意幫助藥物:) – nem035

+0

@ nem035謝謝你添加對象數組相交的正確用法。然而,我會挑剔的,並指出在'intersectionWith'部分,你說'_.isEqual'通過引用來比較對象,這是不正確的。 '_.isEqual'進行深層對象屬性值比較。 – mhodges