Reduce method os array of objects with a condition: is a number?

Viewed 1358

I have an array:

const products = [
    { product: 'banana', price: 3 },
    { product: 'mango', price: 6 },
    { product: 'potato', price: ' ' },
    { product: 'avocado', price: 8 },
    { product: 'coffee', price: 10 },
    { product: 'tea', price: '' },
  ]
  

And Iwould like to sum all prices. What I tried:

const sum = products.reduce(function(acc, cur){
if (Number.isInteger(cur.price))
  return acc+cur.price

  }, 0)
 console.log(sum)

it returns undefined. I also tried that without the condition, it returns a string. Where do I make a mistake?

3 Answers

You need to return the accumulator if the condition is not true.

const
    products = [{ product: 'banana', price: 3 }, { product: 'mango', price: 6 }, { product: 'potato', price: ' ' }, { product: 'avocado', price: 8 }, { product: 'coffee', price: 10  }, { product: 'tea', price: '' }],
    sum = products.reduce(function(acc, cur) {
        if (Number.isInteger(cur.price)) return acc + cur.price;
        else return acc;
    }, 0);
    
console.log(sum);

A shorter approach adds the value conditionally and returns only the accumulator at the end.

const
    products = [{ product: 'banana', price: 3 }, { product: 'mango', price: 6 }, { product: 'potato', price: ' ' }, { product: 'avocado', price: 8 }, { product: 'coffee', price: 10  }, { product: 'tea', price: '' }],
    sum = products.reduce(function(acc, cur) {
        if (Number.isInteger(cur.price)) acc += cur.price;
        return acc;
    }, 0);
    
console.log(sum);

Try this:

const products = [
    { product: 'banana', price: 3 },
    { product: 'mango', price: 6 },
    { product: 'potato', price: ' ' },
    { product: 'avocado', price: 8 },
    { product: 'coffee', price: 10 },
    { product: 'tea', price: '' },
  ]

const sum = products.filter(x => typeof x.price === 'number').map(x => x.price).reduce((a, b) => a + b);
console.log(sum)

The result of your accumulator for the last element tea is undefined because you don't return anything, if price is not a number. And as this is the last call to the accumulator, also the result of reduce is undefined.

If you just want to ignore values with invalid price, you can either use

products.filter(x => Number.isInteger(x.price)).reduce (...)

to only sum up products with a valid price

or return for instance acc if cur.price is not a number.

const sum = products.reduce(function(acc, cur){
  if (Number.isInteger(cur.price)) 
    return acc+cur.price;
  return acc;
  }, 0)
 console.log(sum)
Related