0

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!

2
  • I think you have string concat here. Could you share your input arr too? Commented Sep 7, 2022 at 1:33
  • yes, here: [1849, 81, 64, 36, 25, 16, 9, 9, 4, 1, 0] Commented Sep 7, 2022 at 1:34

1 Answer 1

1
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))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.