๋ฐ˜์‘ํ˜•

flatMap() ๋ฉ”์„œ๋“œ๋Š” ์ฝœ๋ฐฑ์ด ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฐ’์ด ๋ฐฐ์—ด์ด๋ฉด 1 ๋Ž์Šค๊นŒ์ง€ ํŽผ์ณ์„œ ๋ฐ˜ํ™˜ํ•œ๋‹ค. map(), flat() ๋ฉ”์„œ๋“œ๋ฅผ ์ฒด์ด๋‹ํ•œ ๊ฒƒ๊ณผ ๋™์ผํ•œ ํšจ๊ณผ๋ฅผ ๊ฐ€์ง„๋‹ค. e.g. arr.map(...args).flat()

const numbers = [1, 2, 3, 4, 5];
numbers.map((n) => [n * 2]); // [[1], [2], [3], [4], [5]]
numbers.flatMap((n) => [n * 2]); // [2, 4, 6, 8, 10]

const sayHello = ['Hello', 'World'];
sayHello.map((word) => word.split('')); // [['H', 'e', 'l', 'l', 'o'], ['W', 'o', 'r', 'l', 'd']]
sayHello.flatMap((word) => word.split('')); // ['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd']

 

๋งŒ์•ฝ, flatMap()์˜ ์ฝœ๋ฐฑ ํ•จ์ˆ˜๊ฐ€ ๋นˆ ๋ฐฐ์—ด์„ ๋ฐ˜ํ™˜ํ•˜๋ฉด ๊ฒฐ๊ณผ ๋ฐฐ์—ด์— ํฌํ•จ๋˜์ง€ ์•Š๋Š”๋‹ค. ์ด๋ฅผ ํ™œ์šฉํ•˜๋ฉด filter() ๋ฉ”์„œ๋“œ์™€ ๋น„์Šทํ•˜๊ฒŒ ํŠน์ • ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š” ์š”์†Œ๋กœ ์ด๋ค„์ง„ ์ƒˆ๋กœ์šด ๋ฐฐ์—ด์„ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค.

const numbers = [1, 2, 3, 4, 5];
numbers.flatMap((n) => (n % 2 === 0 ? [n] : [])); // [2, 4]

 


๊ธ€ ์ˆ˜์ •์‚ฌํ•ญ์€ ๋…ธ์…˜ ํŽ˜์ด์ง€์— ๊ฐ€์žฅ ๋น ๋ฅด๊ฒŒ ๋ฐ˜์˜๋ฉ๋‹ˆ๋‹ค. ๋งํฌ๋ฅผ ์ฐธ๊ณ ํ•ด ์ฃผ์„ธ์š”
๋ฐ˜์‘ํ˜•