在JavaScript中将一个数组中的相同元素相加
我们需要编写一个包含数字数组的JavaScript函数。
数组中可能包含一些重复/重复的条目。我们的函数应添加所有重复的条目,并返回由此形成的新数组。
示例
为此的代码将是-
const arr = [20, 20, 20, 10, 10, 5, 1];
const sumIdentical = (arr = []) => {
let map = {};
for (let i = 0; i < arr.length; i++) {
let el = arr[i];
map[el] = map[el] ? map[el] + 1 : 1;
};
const res = [];
for (let count in map) {
res.push(map[count] * count);
};
return res;
};
console.log(sumIdentical(arr));输出结果
控制台中的输出将是-
[ 1, 5, 20, 60 ]