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

186
Views
How can I classify this array of object according to age

Hello i have this aray of objects

[{
        name: "person1",
        age: 23,
    },
    {
        name: "person2",
        age: 23,
    },
    {
        name: "person3",
        age: 24,
    },
    {
        name: "person4",
        age: 24,
    },
    {
        name: "person5",
        age: 25,
    }
]

so what i want is to classify this array according to age to get

[
    [{
            name: "person1",
            age: 23,
        },
        {
            name: "person2",
            age: 23,
        }
    ],
    [{
            name: "person3",
            age: 24,
        },
        {
            name: "person4",
            age: 24,
        }
    ],
    [{
        name: "person5",
        age: 25,
    }]
]

I can do it the old fashioned way, but what I want with less code, it's okey to use lodash to get the desired result .

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

0

You could first use reduce to create an object where the items are grouped by age stored as a property, then call Object.values on the result:

const arr=[{name:"person1",age:23},{name:"person2",age:23},{name:"person3",age:24},{name:"person4",age:24},{name:"person5",age:25}];

const byAge = arr.reduce((a,b) => (a[b.age] ? a[b.age].push(b) : a[b.age] = [b], a), {})
const result = Object.values(byAge)
console.log(result)

about 4 years ago · Juan Pablo Isaza Report

0

We can solve this by using lodash

const MockData = [ 
 { name: "person1", age: 23, },
 { name: "person2", age: 23, },
 { name: "person3", age: 24, },
 { name: "person4", age: 24, },
 { name: "person5", age: 25, } ];


 _.groupBy(MockData, 'age'); // we get the desired result !
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!