Javascript - 使用es6计算包含多个字段的对象数组中的重复项

3

我有以下这样一个对象数组。

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

可能是如何在JavaScript中计算数组中重复值的重复项的重复问题。 - Jared Smith
1
你可以使用JSON.stringify([o.x, o.y])或者o.x+'|'+o.y代替o._id,只要它能唯一标识你的对象并适合你的数据类型。 - Bergi
2个回答

6
您可以使用 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)

这里有一个涉及IT技术的解决方案,使用了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)


谢谢!这正是我所需要的。 - bastej

3

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


我可以使用 in 条件来计算对象的值吗?就像这样: no: 3, name: 'drink' }, { no: 90, name: 'eat' }, { no: 20, name: 'swim' } ];``` - Zum Dummi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接