Search⌘ K

Solution to Sub-task: Group

Explore how to group all elements of an array into a single object by iterating mapped arrays, using Object.keys to extract keys and organizing values under corresponding properties. This lesson helps you understand practical approaches to group data effectively in JavaScript.

We'll cover the following...

Group

Group all elements of the array into a single object.

Node.js
// Group
function group (mapped_arr) {
var obj = {}
mapped_arr.forEach(x => {
var key = Object.keys(x)[0]; // assign person
if (key in obj){
// push all elements of x[key] into obj[key]
obj[key].push(Array.from(x[key]));
}
else {
// Assign copy of the array to the object with key
obj[key] = [Array.from(x[key])];
}
})
return obj;
// return an object {(man,friend): [Friends]}
}
var mapped_arr = [
{ 'AB': [ 'B', 'C', 'D' ] },
{ 'AC': [ 'B', 'C', 'D' ] },
{ 'AD': [ 'B', 'C', 'D' ] },
{ 'AB': [ 'A', 'C', 'D', 'E' ] },
{ 'BC': [ 'A', 'C', 'D', 'E' ] },
{ 'BD': [ 'A', 'C', 'D', 'E' ] },
{ 'BE': [ 'A', 'C', 'D', 'E' ] },
{ 'AC': [ 'A', 'B', 'D', 'E' ] },
{ 'BC': [ 'A', 'B', 'D', 'E' ] },
{ 'CD': [ 'A', 'B', 'D', 'E' ] },
{ 'CE': [ 'A', 'B', 'D', 'E' ] },
{ 'AD': [ 'A', 'B', 'C', 'E' ] },
{ 'BD': [ 'A', 'B', 'C', 'E' ] },
{ 'CD': [ 'A', 'B', 'C', 'E' ] },
{ 'DE': [ 'A', 'B', 'C', 'E' ] },
{ 'BE': [ 'B', 'C', 'D' ] },
{ 'CE': [ 'B', 'C', 'D' ] },
{ 'DE': [ 'B', 'C', 'D' ] }
];
console.log(group(mapped_arr));

In the code above, the function group takes only one argument ...