在 JavaScript 中对一个数组中的相同元素求和

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/9 19:56:17

我们需要编写一个 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 ]

相关文章


有用资源