javascript - 在 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}
解决方案
尝试:
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);
推荐阅读
- html - 如何在响应式设计中向右拉出一个元素?
- javascript - 关于如何实现计时器功能的任何帮助或想法
- java - 为什么当我使用带有某些参数的 Mockito 抛出 SqlException 时无法识别?
- python - 为什么它打印出不同的名称?在 Django
- java - 抛出 ClassNotFoundException
- bash - QProcess来自concole的不同输出
- node.js - Vercel 不显示 expressjs 静态文件
- mysql - 在 Django 中用 MySQL 数据库替换 SQLite 数据库
- mongodb - 有没有人能够在 cosmos mongodb 上使用带有日期字段的 ttl?
- python - 如何使用 replit 在 pygame 中显示字体