Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why array with reduce show only one element in a new array?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

help me please!

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading