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'},
]
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'}
]
}
*/
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',
},
];
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);
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;
}, {});
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 })
}
Top comments (0)