首页 > 解决方案 > 在 JavaScript 数组中添加变量

问题描述

嗨,我有一个 JavaScript 数组,看起来如下所示。

{x: red, y: 2}
{x: blue, y: 3}
{x: blue, y; 4}
{x: green, y: 5}

我的问题是,如何添加重复项,所以最后我的数组看起来像下面的代码。

该过程也可以循环完成,因为我实际上有大量数据要以这种方式格式化。

{x: red, y: 2}
{x: blue, y: 7} #the two blue y variables have been added
{x: green, y: 5}

标签: javascriptarrays

解决方案


尝试:

var xs = [];

const data=[{x:"red",y:2},{x:"blue",y:3},{x:"blue",y:4},{x:"green",y:5}];

var n = []
data.forEach((e) => {
  if (!xs.includes(e.x)) { n.push(e); xs.push(e.x) }
  else { n.forEach(f => f.y += f.x == e.x ? e.y : 0) }
})

console.log(n);


推荐阅读