[英]Javascript - Counting duplicates in array of object with many fields in es6
我有像這樣的對象數組。
const array = [ { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 1, y: 2 }, { x: 3, y: 12 } ]
我想計算重復對象並將計數存儲為新對象字段。
我找到了這個片段並且它工作得很好但不完全是我需要的。
const names = [{ _id: 1 }, { _id: 1}, { _id: 2}, { _id: 1}]
const result = [...names.reduce( (mp, o) => {
if (!mp.has(o._id)) mp.set(o._id, Object.assign({ count: 0 }, o));
mp.get(o._id).count++;
return mp;
}, new Map).values()];
console.log(result);
它適用於具有一個字段_id的對象。 就我而言,有兩個,x和y
我該如何修改該代碼?
簡而言之......我想收到結果:
result = [ { x: 1, y: 2, count:3 }, { x: 3, y: 4, count:2 }, { x: 3, y: 12, count:1 } ]
您可以使用Object.values()
和reduce()
方法返回新的對象數組。
const array = [ { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 1, y: 2 }, { x: 3, y: 12 } ] const result = Object.values(array.reduce((r, e) => { let k = `${ex}|${ey}`; if(!r[k]) r[k] = {...e, count: 1} else r[k].count += 1; return r; }, {})) console.log(result)
這是Map
和spread語法的解決方案...
const array = [ { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 1, y: 2 }, { x: 3, y: 12 } ] const result = [...array.reduce((r, e) => { let k = `${ex}|${ey}`; if(!r.has(k)) r.set(k, {...e, count: 1}) else r.get(k).count++ return r; }, new Map).values()] console.log(result)
一種方法是創建一個索引,將x和y映射到結果條目:
let index = { }; let result = [ ]; const array = [ { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 1, y: 2 }, { x: 3, y: 12 } ]; array.forEach(point => { let key = '' + point.x + '||' + point.y; if (key in index) { index[key].count++; } else { let newEntry = { x: point.x, y: point.y, count: 1 }; index[key] = newEntry; result.push(newEntry); } }); console.log(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.