Home > Software engineering >  Why array with reduce show only one element in a new array?
Why array with reduce show only one element in a new array?

Time:09-07

I have this function

let arr = [1849, 81, 64, 36, 25, 16, 9, 9, 4, 1, 0];
    
function reducy(arr){
        return arr.reduce((prevVal, item, index) => {
            prevVal.push(prevVal   item * index);
            return prevVal;
        }, []);
    }

console show this:

//[
  '0',
  '081',
  '0,081128',
  '0,081,0,081128108',
  '0,081,0,081128,0,081,0,081128108100',

but i need:

[0, 81, 128, 108, 100, 80, 54, 63, 32, 9, 0]

help me please!

CodePudding user response:

prevVal.push(prevVal   item * index)

Your problem is you stack value with prevVal which is an array.

The fix should be

prevVal.push(item * index)

Full change

const data = [1849, 81, 64, 36, 25, 16, 9, 9, 4, 1, 0]

function reducy(arr){
    return arr.reduce((prevVal, item, index) => {
        prevVal.push(item * index);
        return prevVal;
    }, []);
}

console.log(reducy(data))

  • Related