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

时间:2017-12-12 14:11:45

标签: javascript ecmascript-6

我有像这样的对象数组。

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 } ]

2 个答案:

答案 0 :(得分:4)

您可以使用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 = `${e.x}|${e.y}`;
  if(!r[k]) r[k] = {...e, count: 1}
  else r[k].count += 1;
  return r;
}, {}))

console.log(result)




以下是Map和展开式语法...

的解决方案



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 = `${e.x}|${e.y}`;
  if(!r.has(k)) r.set(k, {...e, count: 1})
  else r.get(k).count++
  return r;
}, new Map).values()]

console.log(result)




答案 1 :(得分:1)

一种方法是创建一个索引,将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);