Skip to content
Advertisement

Reduce throws “NaN” in JavaScript?

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”

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:

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);
Advertisement