Sum all duplicate value in array - 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

For example βˆ’

If the input array is βˆ’

const input = [1, 3, 1, 3, 5, 7, 5, 4];

Then the output should be βˆ’

const output = [2, 6, 7, 10, 4];

Example

Let’s write the code βˆ’

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{
         return acc;
      }, new Map());
   }
   return Array.from(map, el => el[0] * el[1]);
};
console.log(sumDuplicate(input));

Output

Following is the output in the console βˆ’

[ 2, 9, 10, 7, 4 ]
Updated on: 2020-09-14T13:48:49+05:30

446 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements