- 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 JavaScript arrays repeated value
Suppose, we have an array of objects like this −
const arr = [ {'TR-01':1}, {'TR-02':3}, {'TR-01':3}, {'TR-02':5}];
We are required to write a JavaScript function that takes in one such array and sums the value of all identical keys together.
Therefore, the summed array should look like −
const output = [ {'TR-01':4}, {'TR-02':8}];
Example
The code for this will be −
const arr = [ {'TR-01':1}, {'TR-02':3}, {'TR-01':3}, {'TR-02':5}]; const sumDuplicate = arr => { const map = {}; for(let i = 0; i < arr.length; ){ const key = Object.keys(arr[i])[0]; if(!map.hasOwnProperty(key)){ map[key] = i++; continue; }; arr[map[key]][key] += arr[i][key]; arr.splice(i, 1); }; }; sumDuplicate(arr); console.log(arr);
Output
And the output in the console will be −
[ { 'TR-01': 4 }, { 'TR-02': 8 } ]
Advertisements