Sobes.tech
Junior — Middle+

Grouping an array of users by a selected field with nested ID map creation

livecode

Task condition

It is necessary to group an array of user objects by one of its fields (except id). For each resulting group, create an object (or Map) where:

  • the keys are the id values of users;
  • the values are user objects without the id property.
const users = [
    { id: 1, age: 20, name: "Ivan", country: "Russia", registered: true },
    { id: 2, age: 30, name: "Dima", country: "USA", registered: true },
    { id: 3, age: 25, name: "Lekha", country: "Russia", registered: false },
    { id: 4, age: 20, name: "Lekha", country: "USA", registered: false },
    { id: 5, age: 30, name: "Ivan", country: "Russia", registered: true },
    { id: 6, age: 50, name: "Lekha", country: "Russia", registered: true },
    { id: 7, age: 20, name: "Dima", country: "USA", registered: false }
];

console.log(groupUsers(users, "country"));

/*
{
    "Russia": {
        "1": { age: 20, name: "Ivan", registered: true },
        // ... other users from Russia
    },
    "USA": {
        "2": { age: 30, name: "Dima", registered: true },
        // ... other users from USA
    }
}
*/

The groupUsers function should accept an array and the name of the field to group by, and return the structure described above.