首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >需要帮助在数组中添加/组合项

需要帮助在数组中添加/组合项
EN

Stack Overflow用户
提问于 2017-02-03 17:39:54
回答 1查看 35关注 0票数 1

如果我有一个数组,比如:

代码语言:javascript
运行
AI代码解释
复制
var array = [[1,"GOOG",4],[1,"GOOG",6],[2,"GOOG",4],[2,"FB",4]];

使用javascript,我如何将其转换为数组,其中包含arrayi中相同的第二个值的所有项(在示例中,前3个具有相同的GOOG值,并将它们的第三个值arrayi相加并组合在一起,从而得到以下数组。

代码语言:javascript
运行
AI代码解释
复制
var array = [["GOOG",14],["FB",4]];

编辑:实际上,我需要所有的项目匹配,阿拉伊添加和合并。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-03 17:47:05

代码语言:javascript
运行
AI代码解释
复制
var array = [[1,"GOOG",4],[1,"GOOG",6],[2,"GOOG",4],[2,"FB",4]];

var result = array.reduce(function(acc, item) {
  // check if an item with the same second (item[1]) value already exist
  var index = -1;
  acc.forEach(function(e, i) {
    if(e[0] == item[1])
      index = i;
  });
  
  // if it does exist
  if (index != -1)
    acc[index][1] += item[2]; // add the value of the current item third value (item[2]) to it's second value (acc[index][1])
  // if it does not
  else
    acc.push([item[1], item[2]]); // push a new element

  return acc; // return the accumulator (see reduce docs)
}, []);

console.log(result);

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42035590

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档