
- 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
Sum all duplicate value in array - 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];
Then the output should be −
const output = [2, 6, 7, 10, 4];
Example
Let’s write the code −
const input = [1, 3, 1, 3, 5, 7, 5, 3, 4]; const sumDuplicate = arr => { const map = arr.reduce((acc, val) => { if(acc.has(val)){ acc.set(val, acc.get(val) + 1); }else{ return acc; }, new Map()); } return Array.from(map, el => el[0] * el[1]); }; console.log(sumDuplicate(input));
Output
Following is the output in the console −
[ 2, 9, 10, 7, 4 ]
- Related Articles
- Sum all duplicate values in array in JavaScript
- Finding all duplicate numbers in an array with multiple duplicates in JavaScript
- Sum all similar elements in one array - JavaScript
- Remove the duplicate value from array with images data in JavaScript
- Reverse index value sum of array in JavaScript
- Sum of all prime numbers in an array - JavaScript
- Sum of all positives present in an array in JavaScript
- How to sum all elements in a nested array? JavaScript
- Removing duplicate objects from array in JavaScript
- Find all pairs that sum to a target value in JavaScript
- How to splice duplicate item in array JavaScript
- JavaScript recursive loop to sum all integers from nested array?
- List all duplicate values in a nested JavaScript object
- Sort the array and group all the identical (duplicate) numbers into their separate subarray in JavaScript
- Removing duplicate values in a twodimensional array in JavaScript

Advertisements