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:
JavaScript
x
12
12
1
const array = [
2
{
3
key: '0',
4
value: '10',
5
pair: '2'
6
},
7
{
8
key: '0',
9
value: '10'
10
}
11
];
12
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:
JavaScript
1
3
1
array.reduce((a, b) => a + ((+b.key)+(+b.value)+(+b.pair)), 0)
2
3
So how to handle this “NaN”
Advertisement
Answer
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:
JavaScript
1
16
16
1
const array = [
2
{
3
key: '0',
4
value: '10',
5
pair: '2'
6
},
7
{
8
key: '0',
9
value: '10'
10
}
11
];
12
13
const result = array.reduce((a, b) => a + ((+b.key)+(+b.value)+(+(b.pair ?? 0))), 0);
14
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^
15
// Or +(b.pair || 0)
16
console.log(result);
You don’t need all of those ()
, though:
JavaScript
1
16
16
1
const array = [
2
{
3
key: '0',
4
value: '10',
5
pair: '2'
6
},
7
{
8
key: '0',
9
value: '10'
10
}
11
];
12
13
const result = array.reduce((a, b) => a + ((+b.key)+(+b.value)+(+(b.pair ?? 0))), 0);
14
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^
15
// Or +(b.pair || 0)
16
console.log(result);