How to Find and Group Same Class Elements in a JavaScript Array?

Estimated read time 2 min read

You can use a combination of the Array.prototype.reduce() and Array.prototype.filter() methods to find and group same class elements in a JavaScript array.

Here’s an example that demonstrates how to find and group same class elements in a JavaScript array:

class Person {
  constructor(name, className) {
    this.name = name;
    this.className = className;
  }
}

const people = [
  new Person("John", "A"),
  new Person("Jane", "B"),
  new Person("Jim", "A"),
  new Person("Jack", "C"),
  new Person("Jill", "B")
];

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

console.log(groups);
/*
Output:
{
  A: [
    Person { name: "John", className: "A" },
    Person { name: "Jim", className: "A" }
  ],
  B: [
    Person { name: "Jane", className: "B" },
    Person { name: "Jill", className: "B" }
  ],
  C: [ Person { name: "Jack", className: "C" } ]
}
*/

In this example, the reduce() method is used to iterate over the people array, and the acc object is used to store the groups. The className property of each Person object is used as the key in the acc object, and an array of Person objects is stored as its value. If a key for a certain class doesn’t exist in acc, it is created and its value is set to an empty array. The final result is an object where the keys are the class names and the values are arrays of Person objects belonging to that class.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply