Search code examples
javascriptlodash

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 .


Solution

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