Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

javascript sum array of objects by key

arr.reduce((total, obj) => obj.credit + total,0)
// 3
Comment

sum similar keys in array of objects

const arr = [ { 'name': 'P1', 'value': 150 }, { 'name': 'P1', 'value': 150 }, { 'name': 'P2', 'value': 200 }, { 'name': 'P3', 'value': 450 } ];

const sumByKey = (arr, key, value) => {
  const map = new Map();
  for(const obj of arr) {
    const currSum = map.get(obj[key]) || 0;
    map.set(obj[key], currSum + obj[value]);
  }
  const res = Array.from(map, ([k, v]) => ({[key]: k, [value]: v}));
  return res;
}

console.log(sumByKey(arr, 'name', 'value')); // 'name' = value to group by, 'value' = value to sum
 Run code snippet
Comment

PREVIOUS NEXT
Code Example
Javascript :: Changing the img src using jQuery. 
Javascript :: remove attribute onclick jquery 
Javascript :: js invert color 
Javascript :: how to update kali linux on virtualbox 
Javascript :: save text to file nodejs 
Javascript :: how to get value in formgroup in angular 
Javascript :: how to change text to italic in javascript 
Javascript :: javascript class 
Javascript :: prop-types 
Javascript :: find array with children javascript 
Javascript :: How to calc() height in react native for styling 
Javascript :: install node js 14 
Javascript :: node js timestamp format 
Javascript :: video in react native stack overflow 
Javascript :: react array find index 
Javascript :: axios get status code 
Javascript :: como calcular porcentaje en javascript 
Javascript :: jquery see if checkbox is checked 
Javascript :: jquery hasclass 
Javascript :: settext javascript 
Javascript :: discord.js messageDelete 
Javascript :: how to code localstorages in html 
Javascript :: add element to array javascript 
Javascript :: react native scrollview map 
Javascript :: error handling in express 
Javascript :: Reverse pyramid star pattern in JavaScript 
Javascript :: mongoose delete property 
Javascript :: firebase update users 
Javascript :: Cast to ObjectId failed for value 
Javascript :: __dirname is not defined 
ADD CONTENT
Topic
Content
Source link
Name
8+3 =