Summing all the unique values of an array - JavaScript



Let’s say, 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];

That means all the duplicate ones are summed to index 0 and all the duplicate threes are summed to index 1 and so on.

Example

Following is the code βˆ’

const input = [1, 3, 1, 3, 5, 7, 5, 4];
const mergeDuplicates = 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(mergeDuplicates(input));

Output

This will produce the following output in console βˆ’

[ 2, 6, 10, 7, 4 ]
Updated on: 2020-09-18T12:29:05+05:30

286 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements