2016-04-01 34 views
-1

我有一個要求,根據一定的條件檢查 從數組中刪除重複的對象如果有任何與這個數組中的「連接器」,「地址」,「類型」值相同的對象,我需要刪除該對象。從陣列中刪除重複的發生

array = [{ 
     connector : 'smtp', 
     name : 'john', 
     address : '[email protected]', 
     type : 'cc' 
    }, { 
     connector : 'smtp', 
     name : 'john', 
     address : '[email protected]', 
     type : 'cc' 
    }, { 
     connector : 'gtp', 
     name : 'mark', 
     address : '[email protected]', 
     type : 'cc' 
    }, { 
     connector : 'ftp', 
     name : 'wiki', 
     address : '[email protected]', 
     type : 'bcc' 
    }, 
    { 
     connector : 'smtp', 
     name : 'wiki', 
     address : '[email protected]', 
     type : 'cc' 
    } 
] 

我需要像下面的方式

output = [{ 
     connector : 'smtp', 
     name : 'john', 
     address : '[email protected]', 
     type : 'cc' 
    },{ 
     connector : 'gtp', 
     name : 'mark', 
     address : '[email protected]', 
     type : 'cc' 
    }, { 
     connector : 'ftp', 
     name : 'wiki', 
     address : '[email protected]', 
     type : 'bcc' 
    }, 
    { 
     connector : 'smtp', 
     name : 'wiki', 
     address : '[email protected]', 
     type : 'cc' 
    } 
] 

對不起,我嘗試了一些重複的foreach循環,但最終沒有在那裏輸出。你能幫我找到任何有效的方法嗎?

+0

添加你已經嘗試了代碼 – Tushar

+0

試圖尋找到underscore.js庫。他們有重複的過濾功能。 – binariedMe

回答

2

它可以在下劃線uniq的幫助下完成。

array = [{ 
     connector : 'smtp', 
     name : 'john', 
     address : '[email protected]', 
     type : 'cc' 
    }, { 
     connector : 'smtp', 
     name : 'john', 
     address : '[email protected]', 
     type : 'cc' 
    }, { 
     connector : 'gtp', 
     name : 'mark', 
     address : '[email protected]', 
     type : 'cc' 
    }, { 
     connector : 'ftp', 
     name : 'wiki', 
     address : '[email protected]', 
     type : 'bcc' 
    }, 
    { 
     connector : 'smtp', 
     name : 'wiki', 
     address : '[email protected]', 
     type : 'cc' 
    } 
] 
//generating a string of keys you wish to compare which forms the criteria for uniqueness 
add = _.uniq(array, function(a){ return a.connector + "-" + a.address + "-" + a.type;}) 

console.log(add) 

工作代碼here

+0

'uniqBy'也可以使用。 '_.uniqBy(array,obj => obj.connector +' - '+ obj.address +' - '+ obj.type);' – Tushar

+0

'JSON.stringify'是改進的解決方案,我希望 –

+0

@Tushar你確定關於uniqBy它不存在於文檔http://underscorejs.org/ – Cyril