繁体   English   中英

Javascript - 在es6中用许多字段计算对象数组中的重复项

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM