FrontendDeveloper.in

ECMAScript question detail

GroupBy into objects and maps:

The Object.groupBy() method is used to group object elements of an iterable(like array) based on string values returned from a callback function. It returns an object with each group name as key and respective array of elements as value. The elements in the returned object and the original object are the same. i.e, If you change the internal structure of the elements, it will be reflected in both original and returned object.

In the following example, persons are into categories into several groups based on their age.

const persons = [
{name:"John", age:70},
{name:"Kane", age:5},
{name:"Jack", age:50},
{name:"Rambo", age:15}
];

// Callback function to categorize people based on age
function callbackFunc({ age }) {
if(age >= 60) {
return "senior";
} else if(age > 17 && age < 60) {
return "adult";
}
else {
return "kid";
}
}

const result = Object.groupBy(persons, callbackFunc);

console.log("Kids: ");
for (let [x,y] of result.kid.entries()) {
console.log(y.name + " " + y.age);
}

console.log("Adults: ");
for (let [x,y] of result.adult.entries()) {
console.log(y.name + " " + y.age);
}

console.log("Seniors: ");
for (let [x,y] of result.senior.entries()) {
console.log(y.name + " " + y.age);
}

The Map.groupBy() method is also used to group elements of an object but the result is in the form of a map.

const persons = [
{name:"John", age:70},
{name:"Kane", age:5},
{name:"Jack", age:50},
{name:"Rambo", age:15}
];

// Callback function to categorize people based on age
function callbackFunc({ age }) {
if(age >= 60) {
return "senior";
} else if(age > 17 && age < 60) {
return "adult";
}
else {
return "kid";
}
}

const result = Map.groupBy(persons, callbackFunc);

console.log("Kids: ");
for (let x of result.get("kid")) {
console.log(x.name + " " + x.age);
}

console.log("Adults: ");
for (let x of result.get("adult")) {
console.log(x.name + " " + x.age);
}

console.log("Seniors: ");
for (let x of result.get("senior")) {
console.log(x.name + " " + x.age);
}
Back to all ECMAScript questions
Get LinkedIn Premium at Rs 399