I am trying to create a new array from existing array. Condition is that if element is duplicate then sum those elements. Please see below example for details as may be I am not able to explain clearly:

我正在尝试从现有数组创建一个新的数组。条件是,如果元素是重复的,那么将这些元素相加。详情请见下面的例子,可能我无法解释清楚:

Input:

输入:

var arrayA = ["2", "1", "4", "2", "5", "1", "3", "2"];

Output:

输出:

var arrayB = ["6", "2", "4", "5", "3"];

here arrayB[0] = sum of 2s (2+2+2), arrayB[1] = sum of 1s (1+1)

这里arrayB[0] = 2s(2+2+2)之和,arrayB[1] = 1s(1+1)之和

I tried a lot but not able to figure out how I can achieve this.

我尝试了很多,但没能找到我能做到的方法。

Please help!

请帮助!

5 个解决方案

#1


1

You can do it this way

你可以这样做

 arrayA = ["2", "1", "4", "2", "5", "1", "3", "2"];
 //make a set 
 var set =  new Set(arrayA);
 var arrayB = [];
 set.forEach(function(a) {
   //for each set find in the original arrayA
   var len = arrayA.filter(function(f) {
     return f == a;
   });
   //push in arrayB set element * number of it occurance in original array
   arrayB.push((+a) * (len.length));
 })
 console.log(arrayB)

更多相关文章

  1. 如何将表列转换为数组?
  2. 如何修复JSON对象的假数组?
  3. 如何从SQL SELECT查询中的c#变量创建jQuery数组
  4. 导入地址簿联系人,存储在数组中并保存到数据库
  5. jquery解析php通过ajax传过来的json二维数组对象
  6. 从ajax查询返回的数组看起来还可以,但是它的器官没有正常显示
  7. JQuery攻略(三)数组与字符串
  8. 如何在localStorage中存储数组?(复制)
  9. jquery入门-$.each 数组操作与表单操作代码

随机推荐

  1. 微服务聚合Swagger文档,这波操作是真的香!
  2. Elasticsearch 升级 7.x 版本后,我感觉掉
  3. 我扒了半天源码,终于找到了Oauth2自定义处
  4. 面对成百上千台服务器产生的日志,试试这款
  5. 还在百度Linux命令?推荐一套我用起来特顺
  6. 被我用烂的DEBUG调试技巧,专治各种搜索不
  7. SharePoint 排错: SharePoint Online Ass
  8. 还在手动部署SpringBoot应用?试试这个自动
  9. 微服务应用性能如何?APM监控工具来告诉你!
  10. Mall 电商实战项目发布重大更新,全面支持S