Let's say I have a problem like this there I have an array of objects and I try to use Array.reduce() to count all the numbers of the different types into a new object:
var desks = [
{ type: 'sitting' },
{ type: 'standing' },
{ type: 'sitting' },
{ type: 'sitting' },
{ type: 'standing' }
];
var deskTypes = desks.reduce(function(prev, curr) {
if(curr.type === "sitting") {
return {sitting: ++prev.sitting, standing: prev.standing};
}
if(curr.type === "standing") {
return {sitting: prev.sitting, standing: ++prev.standing};
}
}, { sitting: 0, standing: 0 });
The above example works and everything increments perfectly. Yet, when I switch the ++
to the right side (where I usually place it to increment a value), the function returns NaN
.
var deskTypes = desks.reduce(function(prev, curr) {
if(curr.type === "sitting") {
return {sitting: prev.sitting++, standing: prev.standing};
}
if(curr.type === "standing") {
return {sitting: prev.sitting, standing: prev.standing++};
}
}, { sitting: 0, standing: 0 });
Honestly, I have no idea what's going on here. Can anyone explain?