whatstheoutput_

#45: arr.flatMap(...)

Topic: arrays · Difficulty: ★

console.log([1, 2, 3].flatMap(x => [x, x * 2]));

Output

[ 1, 2, 2, 4, 3, 6 ]

Why

flatMap() is equivalent to calling map() followed by flat(1) in a single, slightly more efficient pass. Here the mapping function turns each number x into a two-element array [x, x*2], so mapping alone would produce a nested array of pairs: [[1,2],[2,4],[3,6]]. flatMap then flattens exactly one level, merging those pairs into a single flat array of six numbers: [1, 2, 2, 4, 3, 6]. It's especially handy when a callback naturally wants to emit zero, one, or many results per input element, avoiding a separate .flat() call afterward.

More arrays puzzles

Play today's puzzle →