Finding the sum of unique array values - 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

Following is the code −

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

This will produce the following output in console −

25
raja
Published on 18-Sep-2020 16:53:33
Advertisements