Sum All Duplicate Values in Array in JavaScript



We are required to write a JavaScript function that takes in an array of numbers with duplicate entries and sums all the duplicate entries to one index.

Example

The code for this will be −

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));

Output

The output in the console −

[ 2, 9, 10, 7, 4 ]
Updated on: 2020-10-14T07:48:31+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements