Sum of Array Object Property Values in New Array of Objects in JavaScript

Better way to sum a property value in an array

Updated Answer

Due to all the downsides of adding a function to the Array prototype, I am updating this answer to provide an alternative that keeps the syntax similar to the syntax originally requested in the question.

class TravellerCollection extends Array {
sum(key) {
return this.reduce((a, b) => a + (b[key] || 0), 0);
}
}
const traveler = new TravellerCollection(...[
{ description: 'Senior', Amount: 50},
{ description: 'Senior', Amount: 50},
{ description: 'Adult', Amount: 75},
{ description: 'Child', Amount: 35},
{ description: 'Infant', Amount: 25 },
]);

console.log(traveler.sum('Amount')); //~> 235

Original Answer

Since it is an array you could add a function to the Array prototype.

traveler = [
{ description: 'Senior', Amount: 50},
{ description: 'Senior', Amount: 50},
{ description: 'Adult', Amount: 75},
{ description: 'Child', Amount: 35},
{ description: 'Infant', Amount: 25 },
];

Array.prototype.sum = function (prop) {
var total = 0
for ( var i = 0, _len = this.length; i < _len; i++ ) {
total += this[i][prop]
}
return total
}

console.log(traveler.sum("Amount"))

The Fiddle: http://jsfiddle.net/9BAmj/

sum all values of an object in an array of objects javascript

Use Array.reduce to calculate the sum

const sum = array.reduce((acc, o) => acc + parseInt(o.value), 0)

Sum of array object property values in new array of objects in Javascript

You can do this with forEach and thisArg optional parameter

var inputArray = [  { subject: 'Maths', marks: '40', noOfStudents: '5' },  { subject: 'Science', marks: '50', noOfStudents: '16' },  { subject: 'History', marks: '35', noOfStudents: '23' },  { subject: 'Science', marks: '65', noOfStudents: '2' },  { subject: 'Maths', marks: '30', noOfStudents: '12' },  { subject: 'History', marks: '55', noOfStudents: '20' },], outputArray = [];  inputArray.forEach(function(e) {  if(!this[e.subject]) {    this[e.subject] = { subject: e.subject, marks:  0, noOfStudents: 0 }     outputArray.push(this[e.subject]);   }  this[e.subject].marks += Number(e.marks);  this[e.subject].noOfStudents += Number(e.noOfStudents);}, {});
console.log(outputArray)

How to sum the array of object values and assigned them to the relevant key name

solved using reduce and forEach

Inside the reduce function I'm running a forEach on the array of keys of the incomes object/attribute. For each key which is a date I'm checking if the accumulator of the reduce function contains an attribute for each date and creates if not. After creating the attribute I'm summing the value for the current date attribute.

const data = [{
group: 'A',
incomes: {
"2019-12": 100,
"2020-12": 200,
"2021-12": 15
}
},
{
group: 'B',
incomes: {
"2019-12": 25,
"2020-12": 50,
}
}
]

const totalIncomes = data.reduce((acc, curr) => {
Object.keys(curr.incomes).forEach((key, index) => {
if (!acc[key]) {
acc[key] = 0
}
acc[key] += curr.incomes[key]
})
return acc
}, {})

console.log(totalIncomes)

Sum all data in array of objects into new array of objects

Using for..in to iterate object and reduce to iterate array

var data = [{costOfAirtickets: 2500, costOfHotel: 1200},{costOfAirtickets: 1500, costOfHotel: 1000}];
var result = [data.reduce((acc, n) => { for (var prop in n) { if (acc.hasOwnProperty(prop)) acc[prop] += n[prop]; else acc[prop] = n[prop]; } return acc;}, {})]console.log(result)

How to sum values in an array of objects in javascript

The following function can be used. I have used ES6. The function takes inputs which will be your input object.

const sumIt = (inputs) => {  const result = {};  inputs.forEach((input) => {    const key = `${input.Daypart}_${input.day_of_week}`;    if (key in result) {      result[key].uplift = result[key].uplift + input.uplift;    } else {      result[key] = { ...input };    }  });  return result;};

SUM all values of an array of objects by array index of object property in JavaScript / JQuery

You could define an array of Ref values for those Vals that you want to include in the calculation and then use reduce and find to get the an array with correct calculation.

const data = [{Ref: "A", Vals: [1,2,3,100]}, {Ref: "B", Vals: [1,2,3,100]}, {Ref: "C", Vals: [1,2,3,100]}]

const result = ['A', 'C'].reduce((r, e) => {
const match = data.find(({ Ref }) => Ref === e);

if (match) {
if (!r) r = match.Vals
else match.Vals.forEach((el, i) => r[i] += el)
}

return r
}, null)

console.log(result)


Related Topics



Leave a reply



Submit