[英]JavaScript - Count and remove duplicates from array of objects ES6
[英]JavaScript - Count and remove duplicates from array of objects with es6
我正在嘗試解決此問題,但是我有點卡住,需要一些幫助/建議。 我試圖越來越了解es6,但是對於解決問題的最佳方法我一無所知。
我要擷取的大型json看起來像這樣:
[
{
"company": "Google",
"location": "USA",
"email": null
},
{
"company": "Microsoft",
"location": "USA",
"email": "mail@mail.com"
},
{
"company": "Google",
"location": "NLD",
"email": "mail@mail.com"
}
]
我將它們顯示在表格中,並希望添加復選框過濾器,但是我也想在其旁邊添加一個計數,如下所示:
[x] Google (2)
[ ] Microsoft (1)
// other function call
[ ] mail@mail.com (2)
我有這個功能,我會呼叫每個按鍵(公司,位置,電子郵件):
function filterArr(data, key) {
data.forEach(element => {
let countedData = data.filter((el) => {
return el[key] == element[key]
}).length;
// console.log(element[key] + ": " + countedData);
});
data = data.filter((item, index, self) => self.findIndex( t => t[key] === item[key] && item[key] != null) === index )
// console.log(data)
return data;
}
filterArr(data, "company");
我嘗試通過上述功能實現的輸出是:Google:2 Microsft:1
foreach正確地計算了鍵值,但顯然記錄了以下內容:Google:2 Microsoft:1 Google:2
過濾器console.log顯示Google和Microsoft(僅一次,就像我想要的那樣:)
現在,我需要將這2種方法結合起來,但是我不確定如何以及最好的方法是什么。 (請參閱我的小提琴: https : //jsfiddle.net/z359qo1d/ )
你知道下一步該怎么做嗎?
Array.prototype.reduce
是您想要的完美匹配
function filterArr(data, key){
return data.reduce( (result, current) => {
if(!result[current[key]]){
result[current[key]] = 1;
} else {
result[current[key]] += 1;
}
return result;
}, {})
}
上面將返回這樣的對象
{
Google: 2,
Microsoft: 1
}
我會做一些不同的事情:
let _in = [
{
"company": "Google",
"location": "USA",
"email": null
},
{
"company": "Microsoft",
"location": "USA",
"email": "mail@mail.com"
},
{
"company": "Google",
"location": "NLD",
"email": "mail@mail.com"
}
]
function countEm(accum, each) {
if (! accum[each.company] )
accum[each.company] = 0
accum[each.company] += 1
return accum
}
console.log(_in.reduce(countEm, {}))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.