Home > Enterprise >  javascript reduce method returns undefined
javascript reduce method returns undefined

Time:07-01

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

Find the sum of price of products using only reduce reduce(callback))

const num=productsg.reduce((acc,a)=>{

    if(typeof a.price=='number'){
        console.log(a.price,acc);
        return acc a.pricex
    }
},0)

give undefined

pls help

CodePudding user response:

You need to always return the accumulator.

const num=productsg.reduce((acc,a)=>{

    if(typeof a.price=='number'){
        console.log(a.price,acc);
        return acc a.pricex
    }
    return acc; 
},0)

CodePudding user response:

You can simplify your reduce using Number

if it's not a valid number it returns 0

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


const num=productsg.reduce((acc,a)=> acc   Number(a.price),0)

console.log(num)

  • Related