创建一个未排序的数组,其中包含重复元素和唯一元素的总和
16lz
2021-01-22
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)
更多相关文章
- 如何将表列转换为数组?
- 如何修复JSON对象的假数组?
- 如何从SQL SELECT查询中的c#变量创建jQuery数组
- 导入地址簿联系人,存储在数组中并保存到数据库
- jquery解析php通过ajax传过来的json二维数组对象
- 从ajax查询返回的数组看起来还可以,但是它的器官没有正常显示
- JQuery攻略(三)数组与字符串
- 如何在localStorage中存储数组?(复制)
- jquery入门-$.each 数组操作与表单操作代码