- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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 in JavaScript
Suppose, we have an array of numbers like this −
const arr = [1, 5, 2, 1, 2, 3, 4, 5, 7, 8, 7, 1];
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:
The output for the array mentioned above will be −
30
Example
The code for this will be −
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 on console −
30
Advertisements