brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Object.groupBy() sorts an array into groups by a key

Javascript
~/tips/tip-javascript-object-groupby

const files = [

Groups the items of an array into an object, one array per key you compute.

Grouping with reduce always makes me read the code twice. There is a built-in for it.

const files = [
  { name: 'a.jpg', type: 'image' },
  { name: 'b.mp4', type: 'video' },
  { name: 'c.png', type: 'image' },
];
const byType = Object.groupBy(files, f => f.type);
// { image: [a.jpg, c.png], video: [b.mp4] }

The callback returns the key for each item, and the result is an object with a property for each group, holding an array of the items in that group.

MDN points out that the result is a null-prototype object. It does not inherit methods such as toString, so a group called constructor or __proto__ cannot break anything. It also means that byType.hasOwnProperty('image') throws, so use Object.hasOwn(byType, 'image') or just check the value.

When the keys are not strings, use Map.groupBy(). MDN recommends it for arbitrary keys such as objects.

The caveat is the age. Object.groupBy is a recent addition to the language, so check the browser support table on MDN and your Node.js version before using it in a project that has to run on older software. For the older browsers, a short reduce still does the job, and it is fine to keep that where support is unclear.

Further reading: MDN: Object.groupBy()

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link