In Javascript, when I need to do a reduction operation, I use the Array.reduce
method.
So:
var valores = [1, 2, 3, 4, 5, 1000];
var resultado = valores.reduce(function (soma, atual) {
return soma + atual;
})
console.log(resultado);
However, when I try to do with Array
of objects, it does not work very well:
var valores = [{valor: 1}, {valor: 2}, {valor: 3}, {valor: 4}, {valor: 5}, {valor: 1000}];
var resultado = valores.reduce(function (soma, atual) {
return soma.valor + atual.valor;
})
console.log(resultado);
In this case, it returns NaN
.
But I'd like to be able to apply the reduction operation on an object to a specific attribute.
How to do this in Javascript?