
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Finding sum of all unique elements in JavaScript
We are required to write a JavaScript function that takes in an array of numbers with duplicate entries and sums all the duplicate entries to one index.
For example: If the input array is −
const input = [1, 3, 1, 3, 5, 7, 5, 4];
Output
Then the output should be −
const output = [2, 6, 7, 10, 4];
// all the duplicate ones are summed to index 0
// all the duplicate threes are summed to index 1 and so on.
Therefore, let’s write the code for this function −
Example
The code for this will be −
const input = [1, 3, 1, 3, 5, 7, 5, 4]; const mergeDuplicates = arr => { const map = arr.reduce((acc, val) => { if(acc.has(val)){ acc.set(val, acc.get(val) + 1); }else{ acc.set(val, 1); }; return acc; }, new Map()); return Array.from(map, el => el[0] * el[1]); }; console.log(mergeDuplicates(input));
Output
The output in the console will be −
[ 2, 6, 10, 7, 4 ]
- Related Articles
- Finding all the unique paths in JavaScript
- Finding the sum of unique array values - JavaScript
- Finding the sum of all common elements within arrays using JavaScript
- Finding sum of alternative elements of the array in JavaScript
- Finding desired sum of elements in an array in JavaScript
- Finding sum of all numbers within a range in JavaScript
- Finding unique elements from Tuple in Python
- Finding three elements with required sum in an array in JavaScript
- Finding sum of multiples in JavaScript
- Sum all similar elements in one array - JavaScript
- Finding unique string in an array in JavaScript
- Finding the element larger than all elements on right - JavaScript
- Finding the group with largest elements with same digit sum in JavaScript
- Program to find sum of unique elements in Python
- Finding lunar sum of Numbers - JavaScript

Advertisements