Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

218
Views
Unable to use array on reduce
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...??

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You should use map() instead:

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

const arr = people.map(p => p.age)
//[20, 19]
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!