Reputation: 81
I am trying to sum items in array. While searching Google and Stack Overflow I found that reduce is a good way of summing an array items. But, when there isn't any key value pair reduce throws error as "Nah", so how to deal with it?
My array exam:
const array = [
{
key: '0',
value: '10',
pair: '2'
},
{
key: '0',
value: '10'
}
];
So from above, I need to calculate all the key values including pair. But when I use it on reduce it gives NaN as the second object doesn't have 'pair',
How to deal this?
My code:
array.reduce((a, b) => a + ((+b.key)+(+b.value)+(+b.pair)), 0)
So how to handle this "NaN"
Upvotes: 2
Views: 553
Reputation: 11001
Use flatMap
, Object.values
and reduce
. (Assuming that we want sum of all the existing key values).
const array = [
{
key: '0',
value: '10',
pair: '2'
},
{
key: '0',
value: '10'
}
];
const sum = array.flatMap(Object.values).reduce((sum, cur) => +cur + sum, 0);
console.log(sum)
Upvotes: 0
Reputation: 1075079
You could use the new nullish coalescing operator, or since you know these are either numbers or non-existent and you want to us 0
in the non-existent case, the logical ||
operator:
const array = [
{
key: '0',
value: '10',
pair: '2'
},
{
key: '0',
value: '10'
}
];
const result = array.reduce((a, b) => a + ((+b.key)+(+b.value)+(+(b.pair ?? 0))), 0);
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^
// Or +(b.pair || 0)
console.log(result);
You don't need all of those ()
, though:
const array = [
{
key: '0',
value: '10',
pair: '2'
},
{
key: '0',
value: '10'
}
];
const result = array.reduce((a, b) => a + ((+b.key)+(+b.value)+(+(b.pair ?? 0))), 0);
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^
// Or +(b.pair || 0)
console.log(result);
Upvotes: 4
Reputation: 28424
You need to get the sum
of the values
in each iteration, and check if the value is a Number
:
const array = [
{ key: '0', value: '10', pair: '2' },
{ key: '0', value: '10' }
];
const res = array.reduce((a, b) =>
a + Object.values(b).reduce((acc, value) => acc + (isNaN(value)?0:+value), 0)
, 0);
console.log(res);
Upvotes: 0
Reputation: 523
Try this,
array.reduce((a, b) => a + ((+b.key||0)+(+b.value||0)+(+b.pair||0)), 0)
Upvotes: 1