chimichanga
chimichanga

Reputation: 191

Sum values of objects in array

I would like to create a sum of an array with multiple objects.

Here is an example: var array = [{"adults":2,"children":3},{"adults":2,"children":1}];

How do I return the sum of adults and the sum of children into a new variable for each?

Thanks, c.

Upvotes: 18

Views: 74951

Answers (9)

Julian
Julian

Reputation: 4366

Here is a fun exercise in functional programming. Assuming you already have a sum function for simple arrays of numbers, you can implement a function that will sum the totals of all keys over an array of objects in just two expressions. No loops, hardcoded property names, anonymous functions or if/else required. I adopted the following code from my answer to How to get an object containing the sum of all items in an arrays of objects? :

var add = (a, b) => a + b;
var sum = _.partial(_.reduce, _, add, 0);

function sumByProperties(data) {
    var keys = _.chain(data)
    .map(_.keys).flatten().uniq().value();
    return _.chain(keys).zip(keys).object()
    .mapObject(_.property)
    .mapObject(_.partial(_.map, data))
    .mapObject(_.compose(sum, _.compact))
    .value();
}

console.log(sumByProperties([{
    apple: 1,
    banana: 4,
    fish: 2,
    melon: 3,
}, {
    apple: 3,
    banana: 2,
    fish: 5,
    melon: 1,
}]));
<script src="https://cdn.jsdelivr.net/npm/[email protected]/underscore-umd-min.js"></script>

While the implementation of sumByProperties is not straightforward, figuring out how it works will deepen your understanding of functional programming. This will empower you to write some things very concisely, such as the definition of sum at the top.

For the convenience of the reader, here are links to the documentation of each Underscore function used in this snippet, by order of evaluation:

_.partial _.reduce _.chain _.map _.keys _.flatten _.uniq _.value _.zip _.object _.mapObject _.property _.partial _.compose _.compact

Upvotes: 0

DINESH Adhikari
DINESH Adhikari

Reputation: 1366

 

var array = [{"adults":2,"children":3},{"adults":2,"children":1}];

var totalChild = array.reduce((accum,item) => accum + item.children, 0)

console.log(totalChild) //output 4

Upvotes: 33

Foxcode
Foxcode

Reputation: 1509

Seeing nobody posted this yet... here is a nice shorthand method:

.reduce((acc, curr) => acc + curr.property, 0)

Example:

arr = [{x:1, y:-1}, {x:2, y:-2}, {x:3, y:-3}];

x_sum = arr.reduce((acc, curr) => acc + curr.x, 0); // 6
y_sum = arr.reduce((acc, curr) => acc + curr.y, 0); // -6

Upvotes: 11

Rayon
Rayon

Reputation: 36609

Use Array.prototype.reduce(), the reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

var array = [{
  "adults": 2,
  "children": 3
}, {
  "adults": 2,
  "children": 1
}];

var val = array.reduce(function(previousValue, currentValue) {
  return {
    adults: previousValue.adults + currentValue.adults,
    children: previousValue.children + currentValue.children
  }
});
console.log(val);

Upvotes: 37

worlf ee
worlf ee

Reputation: 1

May be it can help you and this also without use reduce func.

var sumAdult=0;
var sumChildren=0;
var array = [{
  "adult": 2,
  "children": 3
}, {
  "adult": 2,
  "children": 1
}];
 function x(a,b){
   return a+b;
 }
for (y in array){  
  sumAdult=x(0, array[y].adult);
  console.log( "adult :" + sumAdult);
  sumChildren=x(0, array[y].children);
  console.log( "children :" + sumChildren);
}

Upvotes: -2

Dawid Pura
Dawid Pura

Reputation: 1029

We are not writing code for you, but I suppose you should try:

var val = array.reduce(function (sum, tuple) {
    return { adults: sum.adults + tuple.adults,
             children: sum.children + tuple.children };
});

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

To get a sum of each essence into separate variable:

var array = [{"adults":2,"children":3},{"adults":2,"children":1}];
var adults_sum = 0, children_sum = 0;

array.forEach(function(obj){
    adults_sum += obj["adults"];
    children_sum += obj["children"];
});

console.log(adults_sum, children_sum); // 4 4

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386519

You can write a function for this task, which gets the array to iterate over an the property, which value should be added.

The key feature of the function is the Array#reduce methode and a property which returns the actual count calue and the actual property value.

function count(array, key) {
    return array.reduce(function (r, a) {
        return r + a[key];
    }, 0);
}

var array = [{ "adults": 2, "children": 3 }, { "adults": 2, "children": 2 }],
    adults = count(array, 'adults'),
    children = count(array, 'children');

document.write('Adults: ' + adults + '<br>');
document.write('Children: ' + children + '<br>');

Upvotes: 4

ZigGreen
ZigGreen

Reputation: 178

var array = [{"adults":2,"children":3},{"adults":2,"children":1}];
var sumProps = prop => (sum, obj) => sum += obj[prop];
var adultsCount = array.reduce( sumProps('adults'));
var childrenCount = array.reduce( sumProps('children'));

Upvotes: 1

Related Questions