jquery - Adding values of a particular property from all javascript objects in an array -
i have array of javascript objects:
var myobjects = [{figure: 3}, {figure: 5}, {figure: 2}];
i code give me total of 10 based on addition of figure
properties of objects in myobjects
.
what i've tried/done
i loop through using jquery's .each()
don't feel iterating (and using temporary 'store' variable) elegant.
obviously do:
myobjects[0] + myobjects[1]
etc. - assume there arbitrary amount of objects.
i've done similar getting minimum already:
var lowest = math.min.apply(null, myobjects.map(function (x) { return x['figure']; }));
but equivalent total.
you use array.prototype.reduce:
var data = [{figure: 3}, {figure: 5}, {figure: 2}], sum = data.reduce(function(memo, c) { return memo + c.figure }, 0);
reduce
part of ecmascript 5, available in ie9+ , recent versions of other browsers - see this compatibility table.
Comments
Post a Comment