📜  groubbykey js - Javascript (1)

📅  最后修改于: 2023-12-03 15:31:04.677000             🧑  作者: Mango

GroubByKey in JavaScript

In JavaScript, we can use the reduce function to perform a grouping operation on an array of objects based on a specific key. This is commonly referred to as a "group by" operation.

Example

Let's say we have an array of objects representing people with their ages:

const people = [
  { name: "Alice", age: 20 },
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 20 },
  { name: "Dave", age: 25 },
  { name: "Emily", age: 30 }
];

We can group them by their age as follows:

const groupedPeople = people.reduce((groups, person) => {
  const age = person.age;
  if (!groups[age]) {
    groups[age] = [];
  }
  groups[age].push(person);
  return groups;
}, {});

console.log(groupedPeople);

This will give us the following output:

{
  20: [
    { name: 'Alice', age: 20 },
    { name: 'Charlie', age: 20 }
  ],
  25: [ { name: 'Dave', age: 25 } ],
  30: [
    { name: 'Bob', age: 30 },
    { name: 'Emily', age: 30 }
  ]
}
Explanation

In the code above, we use the reduce function to iterate over the array of people. The second argument to reduce is an object literal {} which serves as the initial value of the groups variable.

We then use an if-statement to check whether the current person's age is already a key in the groups object. If it isn't, we create an empty array for that age key.

Then, we push the current person into the array for the corresponding age key. Finally, we return the groups object.

Conclusion

With the reduce function, it's easy to perform a "group by" operation in JavaScript to group an array of objects by a specific key. This can be useful in a variety of situations, such as analyzing data, generating reports, or creating visualizations.