Reputation: 2922
I've got this array of json objects with these data:
let data = [
{"id_player_team" : 1, "name" : "Jose", "t2p_conv": 3, "t3p_conv": 5},
{"id_player_team" : 2, "name" : "Jesus", "t2p_conv": 2, "t3p_conv": 1},
{"id_player_team" : 3, "name" : "Maria", "t2p_conv": 3, "t3p_conv": 0},
{"id_player_team" : 4, "name" : "Irene", "t2p_conv": 4, "t3p_conv": 2},
{"id_player_team" : 5, "name" : "Carmen", "t2p_conv": 1, "t3p_conv": 2},
];
I want to get the result of the addition of key "t2p_conv". To do this, I use reduce function of javascript, like this:
let sumt2p = data.reduce((acc, item) => {
return acc + item.t2p_conv;
});
console.log("Result: " + sumt2p);
When I try to show the value of sumt2p I've got this result:
Result: [object Object]2341
How is possible that? Am I doing something wrong?
Upvotes: 1
Views: 128
Reputation: 1074198
When you're picking out a property like that, you need to supply the second argument to reduce
to provide a seed value for acc
parameter:
let sumt2p = data.reduce((acc, item) => {
return acc + item.t2p_conv;
}, 0);
// −−^^^
If you don't supply the seed, the first call to your callback uses the first two entries in the array. Since you're using +
on an object (the first object in acc
), it gets converted to a string. :-)
This is one of the many reasons that reduce
is usually more complicated than necessary. Here, for instance, a simple loop, perhaps with destructuring, does the job:
let sumt2p = 0;
for (const {t2p_conv} of data) {
sumt2p += t2p_conv;
}
Upvotes: 7