Search This Blog

2024/03/27

Javascript : Object.groupBy & Object.groupByMap

Object.groupBy():
The Object.groupBy() static method groups the elements of a given
iterable according to the string values returned by a provided callback
function.

The returned object has separate properties for each group, containing
arrays with the elements in the group.

Code:
require("core-js");

const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "raddish", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
{ name: "fish", type: "meat", quantity: 22 },
];

//TypeError: Object.groupBy is not a function if core-js not included
//in Node-v20.5.1

//group inventory elements based on type
var result = Object.groupBy(inventory, (item) => {
return item.type;
});
console.log(result);

Output:
[Object: null prototype] {
vegetables: [
{ name: 'asparagus', type: 'vegetables', quantity: 5 },
{ name: 'raddish', type: 'vegetables', quantity: 5 }
],
fruit: [
{ name: 'bananas', type: 'fruit', quantity: 0 },
{ name: 'cherries', type: 'fruit', quantity: 5 }
],
meat: [
{ name: 'goat', type: 'meat', quantity: 23 },
{ name: 'fish', type: 'meat', quantity: 22 }
]
}
Explanation:
Object.groupBy() return a null-prototype object with properties for
all groups, each assigned to an array containing the elements of the
associated group.Almost all objects in JavaScript ultimately inherit
from Object.prototype. However, you may create null-prototype
objects.
With array.groupBy you can create groups using arbitrary keys. The result is
an regular JavaScript object:

Code:
require("core-js");

const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "raddish", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
{ name: "fish", type: "meat", quantity: 22 },
];

//group inventory element based on if it is veg or non-veg
const result2 = inventory.groupBy((item) => {
return item.type == "meat" ? "Non-Veg" : "Veg";
});
console.log(result2);
console.log(result2["Veg"]);
Output:
[Object: null prototype] {
Veg: [
{ name: 'asparagus', type: 'vegetables', quantity: 5 },
{ name: 'raddish', type: 'vegetables', quantity: 5 },
{ name: 'bananas', type: 'fruit', quantity: 0 },
{ name: 'cherries', type: 'fruit', quantity: 5 }
],
'Non-Veg': [
{ name: 'goat', type: 'meat', quantity: 23 },
{ name: 'fish', type: 'meat', quantity: 22 }
]
}
[
{ name: 'asparagus', type: 'vegetables', quantity: 5 },
{ name: 'raddish', type: 'vegetables', quantity: 5 },
{ name: 'bananas', type: 'fruit', quantity: 0 },
{ name: 'cherries', type: 'fruit', quantity: 5 }
]

Note:
The array.groupByToMap method also let us create groups using arbitrary
keys,but it allows you to use complex types (i.e. objects) as keys.
The result is a Map:

Using Object destructing with groupBy:
Code:
require("core-js");

const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "raddish", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
{ name: "fish", type: "meat", quantity: 22 },
];

//group inventory element based on if it is veg or non-veg
const {Veg,NonVeg} = inventory.groupBy((item) => {
return item.type == "meat" ? "NonVeg" : "Veg";
});
console.log(Veg)
Output:
[
{ name: 'asparagus', type: 'vegetables', quantity: 5 },
{ name: 'raddish', type: 'vegetables', quantity: 5 },
{ name: 'bananas', type: 'fruit', quantity: 0 },
{ name: 'cherries', type: 'fruit', quantity: 5 }
]

Object.groupByToMap():
Object.groupByToMap() static method groups the elements in an array using the
values returned by its callback function. It returns a Map with the unique
values from the callback function as keys, which can be used to access the
array of elements in each group.

Complex types, such as objects, can be used as keys with the groupToMap()
method.

Code:
require("core-js");

const ATHLETES = [
{
name: "Blessing Ogabere",
nationality: "Nigerian",
age: 26,
height: "78ft",
},
{
name: "Usain Bolt",
nationality: "Jamican",
age: 29,
height: "82ft",
},
{
name: "Fred KERLEY",
nationality: "USA",
age: 16,
height: "82ft",
},
{
name: "Oblique SEVILLE",
nationality: "Jamican",
age: 17,
height: "82ft",
},
];
const eligible = { eligible: true };
const ineligible = { ineligible: true };

const eligibilityResult = ATHLETES.groupByToMap((athlete, index, array) => {
return athlete.age > 18 ? eligible : ineligible;
});

console.log(eligibilityResult);
console.log(eligibilityResult.get(eligible));

Output:
Map(2) {
{ eligible: true } => [
{
name: 'Blessing Ogabere',
nationality: 'Nigerian',
age: 26,
height: '78ft'
},
{
name: 'Usain Bolt',
nationality: 'Jamican',
age: 29,
height: '82ft'
}
],
{ ineligible: true } => [
{
name: 'Fred KERLEY',
nationality: 'USA',
age: 16,
height: '82ft'
},
{
name: 'Oblique SEVILLE',
nationality: 'Jamican',
age: 17,
height: '82ft'
}
]
}
[
{
name: 'Blessing Ogabere',
nationality: 'Nigerian',
age: 26,
height: '78ft'
},
{
name: 'Usain Bolt',
nationality: 'Jamican',
age: 29,
height: '82ft'
}
]
Explanation:
The code above uses groupToMap() with an arrow function that returns the
object keys named eligible or ineligible, depending on whether the element
has an age greater than 18. The returned result object is a Map.

In order to obtain an array from a Map we need to call get() with the key to
obtain the array:

Finding number of occurences of word in sentence using groupToMap():
Code:
require("core-js");
const text = "knock knock chop chop buffalo buffalo buffalo";
const words = text.split(" ");

//groupMap variable is map object it groups words
const groupMap = words.groupToMap((word) => word);

//create an array from map object
const wordArray = Array.from(groupMap);

//find count of each word
const wordCount = wordArray.map((m) => {
return [m[0], m[1].length];
});
let wordMap = new Map(wordCount)

//get how many time word "knock" occured.
console.log(wordMap.get("knock"))
Output:
2


Differences between the groupBy and groupToMap methods:

groupBy groupToMap
This returns a new object where each
key is the different keys you sorted with
This returns a Map with the unique
values from the callback function as keys,
which can be used to access the array of elements
in each group
The results returned can be accessed using
the different values that have now been set as keys,
just like in a regular object
The results returned can be accessed using
the get method available in Maps
The values of the key specified for the sorting
are used to
group the array
The custom value you have created is used to group
the array
This does not require a conditional to sort the array This requires a conditional to group the array


No comments:

Post a Comment