Home > front end >  Unable to use array on reduce
Unable to use array on reduce

Time:10-05

Const people = [ { name: 'siddiq', age: 20} , { name: 'anas', age: 19}]

Const arr = people.reduce((acc, curr) => acc.push(curr.age), [])

It is not working. What i want is to creare an array with only ages...??

CodePudding user response:

You should use map() instead:

const people = [ { name: 'siddiq', age: 20} , { name: 'anas', age: 19}]

const arr = people.map(p => p.age)
//[20, 19]

CodePudding user response:

reduce() requires that you return the accumulator from the callback function (since the accumulator might not be a mutable object). push() returns the length of the updated array, so the second iteration tries to do (1).push(curr.age, []), which doesn't work.

The comma operator is useful for this in arrow functions.

Also, there's no reason to push [] onto acc.

const people = [ { name: 'siddiq', age: 20} , { name: 'anas', age: 19}]
const arr = people.reduce((acc, curr) => (acc.push(curr.age), acc), []);

console.log(arr);

CodePudding user response:

Another option is to use the spread syntax to ensure you'll return an array within reduce method in a cleaner and modern way.

const people = [ { name: 'siddiq', age: 20} , { name: 'anas', age: 19}]
const arr = people.reduce((acc, curr) => [...acc, curr.age], []);

console.log(arr);

  • Related