iTranslated by AI
Comparing JavaScript's Native groupBy with Lodash's .groupBy
TL;DR
- The
groupByfunction has been implemented in the JavaScript standard. - As of December 2023, some browsers such as Safari are not yet supported.
- You can achieve the same code volume and readability as Underscore.js or Lodash's
.groupBy()using only native features.
Introduction
It seems groupBy() has been implemented in the JavaScript standard
groupBy, which is frequently used in programming languages and database queries, is a feature that groups data by specifying a particular column or key. It is already included as a standard feature in languages like Python.
Previously, to implement logic similar to groupBy in JavaScript, the following methods were available:
- Use libraries such as Underscore.js or Lodash.
- Use standard functions like
reduce().
What is Underscore.js?
Underscore.js is a type of library used in JavaScript. It has gained popularity by providing over 100 useful functions.
What is Lodash?
Lodash is a lightweight JavaScript utility library. Frequently used processes for arrays, objects, strings, etc., are provided as modules.
Actual Comparison
Lodash Sample Code
The Lodash documentation introduces the following two implementation examples.
We will compare based on these sample codes.
// Lodash
var grouped = _.groupBy([6.1, 4.2, 6.3], Math.floor);
console.log(grouped);
// => { '4': [4.2], '6': [6.1, 6.3] }
// The `_.property` iteratee shorthand.
var grouped = _.groupBy(['one', 'two', 'three'], 'length');
console.log(grouped);
// => { '3': ['one', 'two'], '5': ['three'] }
Previous Alternative Implementation
Previously, it was necessary to use reduce() to implement it as follows.
// Native with reduce()
var grouped = [6.1, 4.2, 6.3].reduce(
(r, v, i, a, k = Math.floor(v)) => ((r[k] || (r[k] = [])).push(v), r),
{}
);
console.log(grouped);
// => { '4': [4.2], '6': [6.1, 6.3] }
// Native with reduce()
var grouped = ['one', 'two', 'three'].reduce(
(r, v, i, a, k = v.length) => ((r[k] || (r[k] = [])).push(v), r),
{}
);
console.log(grouped);
// => { '3': ['one', 'two'], '5': ['three'] }
Alternative Implementation Using Object.groupBy()
By using Object.groupBy(), it is now possible to implement this with nearly the same amount of code as Lodash.
Additionally, since the argument is only v, representing the current element, readability has also improved.
// Native with Object.groupBy()
var grouped = Object.groupBy([6.1, 4.2, 6.3], (num) => Math.floor(num));
console.log(grouped);
// => { '4': [4.2], '6': [6.1, 6.3] }
// Native with Object.groupBy()
var grouped = Object.groupBy(['one', 'two', 'three'], (v) => v.length);
console.log(grouped);
// => { '3': ['one', 'two'], '5': ['three'] }
Summary
While it might feel a bit overdue, I think it's a feature addition I'm personally happy about, as it can be expected to reduce code volume and improve readability.
I hope to see official support in Safari in the future.
Discussion