Summing up unique array values in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of numbers that may contain some duplicate numbers. Our function should return the sum of all the unique elements (elements that only appear once in the array) present in the array.

For example

If the input array is −

const arr = [2, 5, 5, 3, 2, 7, 4, 9, 9, 11];

Then the output should be 25.

We will simply use a for loop, iterate the array and return the sum of unique elements.

Example

The code for this will be −

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

Output

The output in the console will be −

25
raja
Published on 21-Oct-2020 15:26:35
Advertisements