DEV Community

George K.
George K.

Posted on

1

Group objects with Object.groupBy()

Image description

Let's take an array with objects with different values of the key language:

const dictionary = [
    {phrase:'hello', language:'english'},
    {phrase:'hola', language:'spanish'},
    {phrase:'good morning', language:'english'},
    {phrase:'ciao', language:'italian'},
    {phrase:'おはよう', language:'japanese'},
    ]
Enter fullscreen mode Exit fullscreen mode

We can group the entries by language with Object.groupBy() method and get an object with organized phrases inside arrays for each language:

const organized = Object.groupBy(dictionary, ({language})=> language)

/* we get an object with sorted and grouped entries
{
english:[
{phrase: 'hello', language: 'english'},
{phrase: 'good morning', language: 'english'}
],
italian:[
{phrase: 'ciao', language: 'italian'}
],
japanese:[
{phrase: 'おはよう', language: 'japanese'}
],
spanish:[
{phrase: 'hola', language: 'spanish'}
]
}
*/
Enter fullscreen mode Exit fullscreen mode

We can also group by one of the nested properties, for example this data structure:

const veryComplexDictionary = [
{
  phrase: 'hello',
  details: {
    origin: 'earth',
    translations: { spanish: 'hola', italian: 'ciao' },
    meta: { level: 1, category: 'greeting' },
  },
  language: 'english',
},
{
  phrase: 'hola',
  details: {
    origin: 'earth',
    translations: { english: 'hello', italian: 'ciao' },
    meta: { level: 1, category: 'greeting' },
  },
  language: 'spanish',
},
{
  phrase: 'good bye',
  details: {
    origin: 'earth',
    translations: { italian: 'ciao' },
    meta: { level: 2, category: 'farewell' },
  },
  language: 'english',
},
{
  phrase: 'ciao',
  details: {
    origin: 'earth',
    translations: { english: 'hello', spanish: 'hola' },
    meta: { level: 1, category: 'greeting' },
  },
  language: 'italian',
},
{
  phrase: 'おはよう',
  details: {
    origin: 'earth',
    translations: { japanese: 'こんにちは' },
    meta: { level: 2, category: 'greeting' },
  },
  language: 'japanese',
},
];
Enter fullscreen mode Exit fullscreen mode

And let's say we want to group data by category, such as greeting, farewell:

const organizedVeryComplex = Object.groupBy(veryComplexDictionary, ({ details }) => details.meta.category);
console.log(organizedVeryComplex);
Enter fullscreen mode Exit fullscreen mode

Of we can implement the same method with reduce():

const organized = dictionary.reduce((accumulator, item) => {

  const { language } = item; // item is an object, language is the name of a language

  accumulator[language] = accumulator[language] || []; // assign an empty array for the current language or if it exists already assign itself

  accumulator[language].push(item); // push current object into the current language array

  return accumulator;
}, {});
Enter fullscreen mode Exit fullscreen mode

And we can achieve the same results with a for...of loop:

const organized = {};

for (const entry of dictionary) {
  const { phrase, language } = entry

  if (!organized[language]) {
    organized[language] = []
  }

  organized[language].push({ phrase, language })
}
Enter fullscreen mode Exit fullscreen mode

Please say "thank you" by commenting on this post!

Everyone is welcome

Top comments (0)

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay