
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the Sum of Unique Array Values in JavaScript
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
Advertisements