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: flatMap() maps and filters in one pass

Web-Development
~/tips/tip-javascript-array-flatmap

const a = [5, 4, -3, 20, 17, -33, -4, 18];

Maps an array and drops or adds items in one pass by returning arrays.

Chaining .map().filter() or .map().flat() is common, and it creates an extra array in the middle. flatMap() can often replace both steps, and once I saw the trick with empty arrays I started noticing where it fits.

flatMap() calls your function on each item and flattens the result by one level. So returning an array lets you add several items, and returning an empty array removes the item:

const a = [5, 4, -3, 20, 17, -33, -4, 18];

const result = a.flatMap((n) => {
  if (n < 0) return [];                  // drop negatives
  return n % 2 === 0 ? [n] : [n - 1, 1];  // split odd numbers
});
// [4, 1, 4, 20, 16, 1, 18]

A more practical case: turn a list of orders into one list of line items, skipping empty orders:

const items = orders.flatMap((order) => order.items);

Or parse lines and keep only the valid ones:

const ports = lines.flatMap((line) => {
  const n = Number(line);
  return Number.isInteger(n) ? [n] : [];
});

Caveats: it flattens one level only, so flatMap((x) => [[x]]) still leaves nested arrays. If your callback returns a plain value instead of an array, it is just added, so a mistake there is silent. And for readability, a simple .filter().map() is sometimes clearer to the next person, who has to work out why you return empty arrays. MDN also notes that a plain for loop can beat it in performance-critical code, because flatMap() makes temporary arrays.

It works in all major browsers since January 2020.

Further reading: MDN: Array.prototype.flatMap()

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { Save draft All Web-Development tips (67) All topics

Link