Group Arrays in JavaScript using Array.GroupBy

Group Arrays in JavaScript using Array.GroupBy

JavaScript continuously enriches its standard library on strings and arrays. In today's post, I will be discussing the new array group proposal which is currently at stage 3. This new proposal introduces new methods array.groupBy() and array.groupByToMap(). You can get their polyfills from the core-js library.

Let's see examples below to understand how these methods work.

 

Read this blog post or watch the video below to learn more about the JavaScript array.groupBy() and array.groupByToMap() method.

array.groupBy()

Let's say you have the below list of countries, where each country is an object with 2 properties name and continent.

const countries = [
 { name: "Canada", continent: "AMER" },
 { name: "United States of America", continent: "AMER" },
 { name: "India", continent: "ASIA" },
 { name: "Switzerland", continent: "EUROPE" },
 { name: "Germany", continent: "EUROPE" }
];

The above "countries" is an array of country objects.

Let's say you want to group the countries by continent and get results like the below -

{
 "AMER": [
 {
 "name": "Canada",
 "continent": "AMER"
 },
 {
 "name": "United States of America",
 "continent": "AMER"
 }
 ],
 "ASIA": [
 {
 "name": "India",
 "continent": "ASIA"
 }
 ],
 "EUROPE": [
 {
 "name": "Switzerland",
 "continent": "EUROPE"
 },
 {
 "name": "Germany",
 "continent": "EUROPE"
 }
 ]
} 

You can use the new array.groupBy() to create the above grouping. The code will be much cleaner and readable compared to if you want to do this with reduce() function. Below is the code -

const groupByContinent = countries.groupBy((country) => {
 return country.continent;
});
console.log(JSON.stringify(groupByContinent, null, 2));

countries.groupBy((country) => {...}) returns the object where each property has the key as continent and value as an array with the products from the corresponding continent.

array.groupBy(callback) accepts a callback function which is invoked with 3 arguments: the current array item, index and the array itself. The callback should return a string that is treated as the group name where items will be added.

const groupedObject = array.groupBy((item, index, array) => {
 // ...
 return groupNameAsString;
});

array.groupByToMap()

You might want to utilize a Map instead of a regular object on occasion. The advantage of Map is that it can use any data type as a key, whereas the plain object can only use strings and symbols.

In this situation, you can use the new method array.groupByToMap() method. This method works exactly the same way as array.groupBy(), the only difference is that it groups items into a Map instead of a plain JavaScript object.

Here is the code using array.groupByToMap() method -

const groupByContinentMap = countries.groupByToMap((country) => {
 return country.continent;
});
console.log(groupByContinentMap);

Output will be map like shown below -

Map

Conclusion

Welcome the new methods array.groupBy() and array.groupByToMap() if you want to conveniently group the items of an array.

Both functions use a callback parameter that should return the key of the group into which the current items must be added.

array.groupByToMap() groups the items into a Map instance, whereas array.groupBy() groups them into a simple JavaScript object.

Comments

JavaScript Void Operator

JavaScript Void Operator

When an expression is evaluated using the void operator, the result is undefined. This operator is typically used to obtain an undefined primitive value. It's frequently used in conjunction with hyperlinks. When you click a link, your browser usually refreshes the page or loads a new one. When we don't want the browser to refresh or load a new page when we click a hyperlink, we can use javascript:void(0).

The operand 0 can be used in two ways: void(0) or void 0. Both methods are equally effective. JavaScript:void(0) instructs the browser to "do nothing," preventing the page from being reloaded or refreshed. It's useful when we want to insert links that are vital to the webpage without having to reload the page. Using void(0) on such links stops the page from reloading but allows a useful function like updating a value on the webpage to be performed.

Hyperlinks are a popular use of JavaScript:Void(0). When a user clicks a link on a page, a new page loads in most cases, however this is not always the desired outcome. You could wish to change the value of a field in a form or the value of a variable when a user clicks a link on a website, for example. The void(0) function is used to prevent a website from refreshing when a link is clicked.

Read this blog post or watch the video below to learn more about the JavaScript void operator.

How does void operator work in JavaScript?

Not returning function in JavaScript always works with a void operator.

void 0; // => Undefined
void function helloWorld(){
 //code
}
//The above function actually implemented like this
function helloWorld(){
 return undefined;
}
//Another example
<a href="JavaScript:void(0);"/>

Example 1 

In the below example, I. am defining two links. The first link is using the JavaScript void function whereas the second link is using alert. 

When the first link will be clicked, it will do nothing as the void function is being used, but in case of the second link, the alert will be displayed.

<body>
 <center>
 <h1>JavaScript Void Function</h1>
 <h2>
 Click on both the links to check the difference
 </h2> 
 <h4>
 Link 1 is using JavaScript Void Function
 </h4>
 <a href = "javascript:void(0);">Link 1</a>
 <h4>
 Link 1 is using JavaScript Alert Function
 </h4>
 <a href = "javascript:alert('Technical Potpourri');">Link 2</a>
 </center>
</body>
JavaScript Void Function

Example 2

In the below example, when I double-click the link, it will show the message but not redirect you to the page. The reason is the JavaScript void function is being used.

<body>
 <center>
 <h1>JavaScript Void Function</h1>
 <a href = "javasctipt:void(0);https://www.sudipta-deb.in/" ondblclick = "alert('Welcome to the Technical Potpourri')">  Double click the link  </a> 
 </center>
</body> 
JavaScript Void Function

Conclusion

The void operator is used when a function does not return anything, when an undefined primitive value is desired, and when javascript:void(0) links are not usable.

Comments