- 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
Sum of distinct elements of an array - JavaScript
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: Suppose, we have an array of numbers like this −
const arr = [1, 5, 2, 1, 2, 3, 4, 5, 7, 8, 7, 1];
The output for the array mentioned above will be 20.
Example
Following is the code −
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 in the console −
30
- Related Articles
- Sum of distinct elements of an array in JavaScript
- Sum of all the non-repeating elements of an array JavaScript
- Absolute sum of array elements - JavaScript
- Thrice sum of elements of array - JavaScript
- Finding desired sum of elements in an array in JavaScript
- Pair of (adjacent) elements of an array whose sum is lowest JavaScript
- Find sum of non-repeating (distinct) elements in an arrays in C++
- Product of non-repeating (distinct) elements in an Array in C++
- Maximum sum of n consecutive elements of array in JavaScript
- Finding sum of alternative elements of the array in JavaScript
- Count distinct elements in an array in Python
- Count distinct elements in an array in C++
- Compute the sum of elements of an array which can be null or undefined JavaScript
- Rearranging elements of an array in JavaScript
- Alternating sum of elements of a two-dimensional array using JavaScript

Advertisements