2016-05-04 57 views
2

我有一個數組,可以簡化讓我們說第一個,最後一個和年齡的人。我想創建一個所有具有相同姓氏,相同姓氏和同一年齡的人的新陣列。例如我的出發陣列:lodash javascript數組匹配多個參數的重複項

[ 
    {id: 1, first: 'fred', last: 'smith', age: 21}, 
    {id: 2, first: 'fred', last: 'smith', age: 21}, 
    {id: 3, first: 'tom', last: 'smith', age: 21}, 
    {id: 4, first: 'fred', last: 'smith', age: 32} 
] 

我想返回匹配第一是/最後/年齡重複:

[ 
    {id: 1, first: 'fred', last: 'smith', age: 21}, 
    {id: 2, first: 'fred', last: 'smith', age: 21} 
] 

我與_.uniq努力找出如何做到這一點,任何幫助表示讚賞。

+1

會'。降低()'你想要做什麼?比較每個項目與以前,如果他們匹配,返回後面? – evolutionxbox

+0

如果有2個fred和2個toms,會發生什麼?你期待什麼? –

+0

@菲利普斯金納,如果有2個姓氏和年齡相同的家庭成員,他們應該包括在內,如果有2名同姓和年齡相同的湯姆斯,他們也應該包括在內,基本上所有符合所有三項標準的記錄。 – edencorbin

回答

3

您可以利用_.groupBy()對值進行分組,確保它是按您確定爲重複條件的值進行分組。然後你可以用_.filter()每個分組的值按它們累加的數組的長度,然後用_.flatten()來獲得最終的數組。

var data = [ 
 
    {id: 1, first: 'fred', last: 'smith', age: 21}, 
 
    {id: 2, first: 'fred', last: 'smith', age: 21}, 
 
    {id: 3, first: 'tom', last: 'smith', age: 21}, 
 
    {id: 4, first: 'fred', last: 'smith', age: 32} 
 
]; 
 

 
var result = _(data) 
 
    .groupBy(i => _(i).pick('first', 'last', 'age').values().value()) 
 
    .filter(i => i.length > 1) 
 
    .flatten() 
 
    .value(); 
 

 
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.js"></script>

+0

工作完美,謝謝。 – edencorbin

+0

感謝您向我介紹'pick'的多屬性形式。 –