What will be the value of the 'acc' and 'curr' here ? It doesn't even logging the values from the reducer function

let array = [{amount: 10, name: 'laptop'}];

const reducer = (acc, curr) => {

    console.log(acc + " is acc");

    console.log(curr + " is curr");

    return acc.amount + curr.amount;

}

const reduced = array.reduce(reducer);

console.log(reduced);

I wanted the value of the amount but instead getting the whole object when my array contains only one value.

Understanding reduce method was hard for me.

Reducer function is called for every element of the given array.
You have only one element in the array, the object with ‘amount’ and ‘name’ keys.

Try to learn reduce function in a simpler setup.

Go here, change some numbers, edit the function. Then change those numbers with objects.

Reduce is useful on arrays that are longer than 1 element.

I know and I am seeing that it isn’t working but why it is returning the whole object instead of amount what is curr value in the reduce function now. these explanation is not present in the w3school.com

if you don’t set a starting value, the starting value of the reducer is the first element in the array, as there are no other values to iterate through, it just returns it

1 Like

If you want to learn about the Reduce method I would suggest you read the MDN page, not w3schools. They do not even come close to being equivalent.

Using reduce to extract a single value from an object doesn’t make much sense. But as said all you need is a starting value and to do the addition to the correct values.

let array = [{amount: 10, name: 'laptop'}];

const reducer = (acc, curr) => acc + curr.amount
const reduced = array.reduce(reducer, 0);

console.log(reduced); // 10

You can forgo the accumulator as well. Now, it makes even less sense.

let array = [{amount: 10, name: 'laptop'}];

const reducer = (_, curr) => curr.amount

const reduced = array.reduce(reducer, 0);

console.log(reduced); // 10

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.