- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Summing up 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
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
- Related Articles
- Summing all the unique values of an array - JavaScript
- Combine unique items of an array of arrays while summing values - JavaScript
- Summing up to amount with fewest coins in JavaScript
- Summing up digits and finding nearest prime in JavaScript
- Filter unique array values and sum in JavaScript
- Extract unique values from an array - JavaScript
- Finding the sum of unique array values - JavaScript
- JavaScript - summing numbers from strings nested in array
- How to get all unique values in a JavaScript array?
- Summing array of string numbers using JavaScript
- Find unique and biggest string values from an array in JavaScript
- When summing values from 2 arrays how can I cap the value in the new JavaScript array?
- Modified version of summing an array with recursion in JavaScript
- Making array unique in JavaScript
- JavaScript: How to filter out Non-Unique Values from an Array?

Advertisements