Home > Net >  Trying to get a sum using reduce method
Trying to get a sum using reduce method

Time:09-22

I am trying to get the sum of all (a) properties and console.log says NAN

const numbers = [{ a: 1 }, { a: 6 }, { a: 3 }, { d: 4 }, { e: 5 }, { f: 5 }];

const filterNumbers = numbers.reduce((currenttotal, item) => {
  return item.a   currenttotal;
}, 0);
console.log(filterNumbers);

is there something wrong? trying to get the sum of only a keys

CodePudding user response:

Not all elements have an a key. If you want to dynamically get whichever key is present, this should work:

const numbers = [{ a: 1 }, { a: 6 }, { a: 3 }, { d: 4 }, { e: 5 }, { f: 5 }];

const filterNumbers = numbers.reduce((currenttotal, item) => {
    let keys = Object.keys(item);
    return item[keys[0]]   currenttotal;
}, 0);
console.log(filterNumbers);

CodePudding user response:

Hate to be the person that takes someone's comment and makes an answer out of it, but as @dandavis has suggested, you need to, in someway, default to a value if the 'a' key doensn't exist.

This can be done in a variety of ways:

Short circuit evaluation:

const filterNumbers = numbers.reduce((currenttotal, item) => {
  return (item.a || 0)   currenttotal;
}, 0);

The in operator:

const filterNumbers = numbers.reduce((currenttotal, item) => {
  return ("a" in item ? item.a : 0)   currenttotal;
}, 0);

Nullish coalescing operator:

const filterNumbers = numbers.reduce((currenttotal, item) => {
  return (item.a ?? 0)   currenttotal;
}, 0);

Checking for falsey values of item.a (basically longer short circuit evaluation):

const filterNumbers = numbers.reduce((currenttotal, item) => {
  return (item.a ? item.a : 0)   currenttotal;
}, 0);

CodePudding user response:

Since not all fields have an a key the reduce does not find a value and return NAN.

The solution it`s the same as the previous answer, but i rather use immutability in variables since prevents future erros.

const numbers = [{ a: 1 }, { a: 6 }, { a: 3 }, { d: 4 }, { e: 5 }, { f: 5 }];

const filterNumbers = numbers.reduce((currenttotal, item) => {
    const keys = Object.keys(item);
    return item[keys[0]]   currenttotal;
}, 0);
console.log(filterNumbers);

and in the case u need to sum only with the specific key:

const filterNumbers = numbers.reduce((currenttotal, item) => {
   return (item.a ?? 0)   currenttotal;
}, 0);
console.log(filterNumbers);
  • Related