使用 JavaScript 对数组中的所有重复值求和

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/25 0:44:17

我们需要编写一个 JavaScript 函数,该函数接受一个包含重复条目的数字数组,并将所有重复条目求和到一个索引。

示例

其代码为 −

const input = [1, 3, 1, 3, 5, 7, 5, 3, 4];
const sumDuplicate = arr => {
   const map = arr.reduce((acc, val) => {
      if(acc.has(val)){
         acc.set(val, acc.get(val) + 1);
      }else{
         acc.set(val, 1);
      };
      return acc;
   }, new Map());
   return Array.from(map, el => el[0] * el[1]);
};
console.log(sumDuplicate(input));

输出

控制台中的输出 −

[ 2, 9, 10, 7, 4 ]

相关文章


有用资源