GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • The `setTimeout()` Function in JavaScript
  • How to Get Distinct Values in a JavaScript Array
  • Check if a Date is Valid in JavaScript
  • Encode base64 in JavaScript
  • Check if URL Contains a String
  • JavaScript Add Month to Date
  • JavaScript Add Days to Date
  • Fundamentals
  • Node
  • Vue
  • Webpack
  • Axios
  • Mongoose
  • Express

This view

  • Original page
  • New address

GeezerVison is showing masteringjs.io — JavaScript Array flatMap()

Mastering JS Logo
Mastering JS
Tutorials Newsletter eBooks Jobs
☰
Tutorials Newsletter eBooks Jobs
Tutorials / Fundamentals /

JavaScript Array flatMap()

May 25, 2024

The flatMap() method on JavaScript arrays combines map() and flat() into one call.

flatMap() takes a callback parameter and calls callback() on every element in the array. If callback returns some value that is not an array, then flatMap() behaves identically to map(), adding the returned value to the result array.

const arr = ['a', 'b', 'c'];

arr.flatMap(function callback(el) {
  return el.toUpperCase();
}); // ['A', 'B', 'C']

If callback returns an array, then flatMap() "flattens" that array and adds each element from the returned value to the result array.

const arr = [
  { title: 'Intro to JavaScript Arrays', tags: ['fundamentals', 'arrays'] },
  { title: 'Intro to Mongoose Arrays', tags: ['mongoose', 'arrays'] }
];

arr.flatMap(el => el.tags); // ['fundamentals', 'arrays', 'mongoose', 'arrays']

In the above example, flatMap() would be useful for removing duplicates from an array of arrays:

const arr = [
  { title: 'Intro to JavaScript Arrays', tags: ['fundamentals', 'arrays'] },
  { title: 'Intro to Mongoose Arrays', tags: ['mongoose', 'arrays'] }
];

// Remove duplicate `tags` entries
[...new Set(arr.flatMap(el => el.tags)]; // ['fundamentals', 'arrays', 'mongoose']

Combining map() and filter()

Another neat trick with flatMap() is you can combine map() and filter() into one function call. If your flatMap() callback returns an empty array, flatMap() won't add anything to the result array.

const numbers = [1, 2, 3, 4, 5];

// [1, 3, 5]
arr.flatMap(function filterEvenNumbers(num) {
  if (num % 2 === 0) {
    // returning empty array means `flatMap()` will skip this value
    return [];
  }
  return num;
});

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials

  • The `setTimeout()` Function in JavaScript
  • How to Get Distinct Values in a JavaScript Array
  • Check if a Date is Valid in JavaScript
  • Encode base64 in JavaScript
  • Check if URL Contains a String
  • JavaScript Add Month to Date
  • JavaScript Add Days to Date
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.