
- 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 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 } ]
- Related Articles
- Sum arrays repeated value - JavaScript
- Adding two arrays of objects with existing and repeated members of two JavaScript arrays replacing the repeated ones
- Repeated sum of Number’s digits in JavaScript
- Reverse sum of two arrays in JavaScript
- Multiply and Sum Two Arrays in JavaScript
- Partial sum in array of arrays JavaScript
- Concatenate two arrays of objects and remove repeated data from an attribute in JavaScript?
- Column sum of elements of 2-D arrays in JavaScript
- Finding the sum of all common elements within arrays using JavaScript
- Sum all duplicate value in array - JavaScript
- MySQL query to sum rows having repeated corresponding Id
- Reverse index value sum of array in JavaScript
- How to workaround Objects vs arrays in JavaScript for key/value pairs?
- Javascript typed arrays
- JavaScript JSON Arrays

Advertisements