CodewCaro.

How to Group Arrays in JavaScript

Caroline Cah
Caroline Cah

Working with arrays in JavaScript is a common task, but sometimes you need to group the elements of an array based on some criteria. In this tutorial, we'll explore different ways of grouping arrays in JavaScript.


const arr = ["apple", "banana", "cherry", "date", "elderberry", "fig"];
const grouped = {};

for (const item of arr) {
  const firstLetter = item[0];
  if (grouped[firstLetter]) {
    grouped[firstLetter].push(item);
  } else {
    grouped[firstLetter] = [item];
  }
}

console.log(grouped); // { a: [ 'apple' ], b: [ 'banana' ], c: [ 'cherry' ], d: [ 'date' ], e: [ 'elderberry' ], f: [ 'fig' ] }

Here, we first declare an empty object called grouped.Then, we loop through each element of the arr array and extract its first letter using item[0]. We check if groupedalready has a property with the name of the first letter; if it does, we push the current item to that property's array. If it doesn't, we create a new property with the name of the first letter and assign it an array containing the current item.


Another way to group arrays in JavaScript is by using the reduce method. Here's how it works:


const arr = ["apple", "banana", "cherry", "date", "elderberry", "fig"];
const grouped = arr.reduce((acc, item) => {
  const firstLetter = item[0];
  if (!acc[firstLetter]) {
    acc[firstLetter] = [];
  }
  acc[firstLetter].push(item);
  return acc;
}, {});

console.log(grouped); // { a: [ 'apple' ], b: [ 'banana' ], c: [ 'cherry' ], d: [ 'date' ], e: [ 'elderberry' ], f: [ 'fig' ] }

Here, we first declare an empty object and pass it as the initial value for the reduce method. Then, for each item in the array, we extract its first letter and check if the acc accumulator object already has a property with that name. If it doesn't, we create a new property with an empty array. Then, we push the current item to the array associated with the first letter, and return the accumulator object.


Conclusion


Grouping arrays in JavaScript can be achieved in several ways, depending on your coding style and performance requirements. Whether you use a for loop and an object or the reduce method, grouping arrays can help you organize and manipulate data more efficiently.

More posts