sum object values javascript code example
Example 1: javascript object total
function sum( obj ) {
var sum = 0;
for( var el in obj ) {
if( obj.hasOwnProperty( el ) ) {
sum += parseFloat( obj[el] );
}
}
return sum;
}
var sample = { a: 1 , b: 2 , c:3 };
var summed = sum( sample );
console.log( "sum: "+summed );
Example 2: javascript sum of number in object array
run.addEventListener("click", function () {
let sum = people.reduce(function (a, b) {
return {
age: a.age + b.age,
};
});
console.log(sum);
});
Example 3: javascript object array sum of values in object
const fruitTally = fruit.reduce((currentTally, currentFruit) => {
currentTally[currentFruit] = (currentTally[currentFruit] || 0) + 1
return currentTally
} , {})