18 votes

La fonction de réduction des tableaux renvoie NAN

J'ai un code similaire au suivant :

var temp=[{"name":"Agency","y":32,"drilldown":{"name":"Agency","categories":["APPS & SI","ERS"],"data":[24,8]}},{"name":"ER","y":60,"drilldown":{"name":"ER","categories":["APPS & SI","ERS"],"data":[7,53]}},{"name":"Direct","y":60,"drilldown":{"name":"Direct","categories":["APPS & SI","ERS"],"data":[31,29]}}];

var reduced=temp.reduce(function (a,b) {
        return a.y + b.y;
    });
console.log(reduced) // returns NAN

44voto

Nina Scholz Points 17120

Vous pourriez utiliser une valeur de départ et n'ajouter qu'une seule valeur du tableau.

var temp=[{"name":"Agency","y":32,"drilldown":{"name":"Agency","categories":["APPS & SI","ERS"],"data":[24,8]}},{"name":"ER","y":60,"drilldown":{"name":"ER","categories":["APPS & SI","ERS"],"data":[7,53]}},{"name":"Direct","y":60,"drilldown":{"name":"Direct","categories":["APPS & SI","ERS"],"data":[31,29]}}];

var reduced = temp.reduce(function (r, a) {
        return r + a.y;
        //    ^^^ use the last result without property
    }, 0);
//   ^^^ add a start value
console.log(reduced) // r

9voto

Chen Points 650

Solution courte : mapper la collection vers une collection d'entiers, et la réduire.

var temp=[{"name":"Agency","y":32,"drilldown":{"name":"Agency","categories":["APPS & SI","ERS"],"data":[24,8]}},{"name":"ER","y":60,"drilldown":{"name":"ER","categories":["APPS & SI","ERS"],"data":[7,53]}},{"name":"Direct","y":60,"drilldown":{"name":"Direct","categories":["APPS & SI","ERS"],"data":[31,29]}}];

var reduced = temp
                .map(function(obj) { return obj.y; })
                .reduce(function(a, b) { return a + b; });

console.log(reduced);

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X