Sum of distinct elements of an array in JavaScript


Suppose, we have an array of numbers like this −

const arr = [1, 5, 2, 1, 2, 3, 4, 5, 7, 8, 7, 1];

We are required to write a JavaScript function that takes in one such array and counts the sum of all distinct elements of the array.

For example:

The output for the array mentioned above will be −

30

Example

The code for this will be −

const arr = [1, 5, 2, 1, 2, 3, 4, 5, 7, 8, 7, 1];
const distinctSum = arr => {
   let res = 0;
   for(let i = 0; i < arr.length; i++){
      if(i === arr.lastIndexOf(arr[i])){
         res += arr[i];
      };
      continue;
   };
   return res;
};
console.log(distinctSum(arr));

Output

Following is the output on console −

30

Updated on: 10-Oct-2020

159 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements