- 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 identical elements within one array in JavaScript
We are required to write a JavaScript function that takes in an array of Numbers.
The array might contain some repeating / duplicate entries within it. Our function should add all the duplicate entries and return the new array thus formed.
Example
The code for this will be −
const arr = [20, 20, 20, 10, 10, 5, 1]; const sumIdentical = (arr = []) => { let map = {}; for (let i = 0; i < arr.length; i++) { let el = arr[i]; map[el] = map[el] ? map[el] + 1 : 1; }; const res = []; for (let count in map) { res.push(map[count] * count); }; return res; }; console.log(sumIdentical(arr));
Output
And the output in the console will be −
[ 1, 5, 20, 60 ]
- Related Articles
- Sum all similar elements in one array - JavaScript
- Adding up identical elements in JavaScript
- Consecutive elements sum array in JavaScript
- Check if three consecutive elements in an array is identical in JavaScript
- Sum similar numeric values within array of objects - JavaScript
- Absolute sum of array elements - JavaScript
- Finding the sum of all common elements within arrays using JavaScript
- How to redundantly remove duplicate elements within an array – JavaScript?
- Chunking array within array in JavaScript
- Thrice sum of elements of array - JavaScript
- Sum of distinct elements of an array in JavaScript
- Sum of distinct elements of an array - JavaScript
- Finding desired sum of elements in an array in JavaScript
- How to sum all elements in a nested array? JavaScript
- Maximum sum of n consecutive elements of array in JavaScript

Advertisements