Sobes.tech
Middle

Task: implement a function to group users by city (groupByCity).

sobes.tech AI

Answer from AI

To group users by city, you can use the reduce method or forEach with a dictionary object. Here's an example in JavaScript:

function groupByCity(users) {
  return users.reduce((acc, user) => {
    const city = user.city;
    if (!acc[city]) {
      acc[city] = [];
    }
    acc[city].push(user);
    return acc;
  }, {});
}

// Example usage:
const users = [
  { id: 1, name: 'Ivan', city: 'Moscow' },
  { id: 2, name: 'Anna', city: 'Saint Petersburg' },
  { id: 3, name: 'Pyotr', city: 'Moscow' }
];

const grouped = groupByCity(users);
console.log(grouped);
/*
{
  Moscow: [ { id: 1, name: 'Ivan', city: 'Moscow' }, { id: 3, name: 'Pyotr', city: 'Moscow' } ],
  'Saint Petersburg': [ { id: 2, name: 'Anna', city: 'Saint Petersburg' } ]
}
*/

This approach creates an object where the key is the city name, and the value is an array of users from that city.

Task: implement a function to group users by city… - sobes.tech