4
In Javascript, when I need to do a reduction operation, I use the method Array.reduce
.
Thus:
var valores = [1, 2, 3, 4, 5, 1000];
var resultado = valores.reduce(function (soma, atual) {
return soma + atual;
})
console.log(resultado);
But when I try to do it with a Array
of objects, it doesn’t 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, returns NaN
.
But I wish I could apply the reduction operation on an object in a certain specific attribute.
How to do this in Javascript?
by what seems the objects that are read first are the
valor1
andvalor2
, after that the first valuesoma
begins to beundefined
. put aconsole.log
in place of thereduce
and you will see.– RFL
Related: https://answall.com/q/161754/101 Also: https://answall.com/q/195126/101
– Maniero