How to Skip Elements in JavaScript Arrays Using flatMap
This article explains how JavaScript's map, filter, and especially flatMap methods can be used to transform arrays while selectively skipping or removing elements, offering concise code examples that demonstrate replacing separate map‑filter chains with a single flatMap call for cleaner, more efficient array processing.
The map() method creates a new array whose elements are the results of calling a provided function on each element of the original array.
const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]Sometimes we need to skip certain elements; for example, to skip the element 1 we can combine filter with map:
const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1
.filter(x => x !== 1)
.map(x => x * 2);
console.log(map1);
// expected output: Array [8, 18, 32]While using map and filter together works, the code can become less readable. A shorter approach is to use flatMap, which first maps each element and then flattens the result into a new array, effectively combining mapping and filtering in one step.
const array1 = [1, 4, 9, 16];
// use flatMap to skip element 1
const map1 = array1.flatMap(x => x === 1 ? [] : [x * 2]);
console.log(map1);
// expected output: Array [8, 18, 32] flatMapcan add or remove items during the mapping phase: returning a single‑element array keeps the item, returning a multi‑element array adds items, and returning an empty array removes the item, making it functionally opposite to filter.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
JavaScript
Provides JavaScript enthusiasts with tutorials and experience sharing on web front‑end technologies, including JavaScript, Node.js, Deno, Vue.js, React, Angular, HTML5, CSS3, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
