μ–Έμ–΄/Script Question

map & flat & flatMap

MellowHoney 2024. 4. 7. 14:18
728x90
λ°˜μ‘ν˜•

map()

μ„€λͺ…

πŸ’‘ 콜백 ν•¨μˆ˜μ˜ λ¦¬ν„΄κ°’μœΌλ‘œ 이뀄진 μƒˆλ‘œμš΄ 배열을 μƒμ„±ν•˜λŠ” ν•¨μˆ˜ 

μ‚¬μš©λ²•

array.map(callback[, thisArg])
// arr : 원본 λ°°μ—΄
// callback (ν•„μˆ˜) : 원본 λ°°μ—΄μ˜ 각 μš”μ†Œμ— λŒ€ν•΄ μ‹€ν–‰ν•  ν•¨μˆ˜μ΄λ©° μš”μ†Œ, 인덱슀, λ°°μ—΄ 전체λ₯Ό λ§€κ°œλ³€μˆ˜λ‘œ λ°›μŒ
// thisArg (선택) : 콜백 ν•¨μˆ˜ λ‚΄μ—μ„œ μ‚¬μš©ν•  this κ°’, 콜백 ν•¨μˆ˜μ˜ this κ°’ μ§€μ • κ°€λŠ₯

μ˜ˆμ‹œ

const arr = [1, 2, 3];

const newArr = arr.map((num) => num * 2);
console.log(newArr); // map 리턴값 : [2, 4, 6]
console.log(arr); // 원본 λ°°μ—΄ : [1, 2, 3]

flat()

μ„€λͺ…

πŸ’‘ 쀑첩 λ°°μ—΄ ꡬ쑰λ₯Ό 평탄화 μ‹œν‚€κΈ° μœ„ν•΄ μ‚¬μš©

μ‚¬μš©λ²•

array.flat([depth: number | Infinity]); 
// depth default : 1
// option - Infinity : ν•˜μœ„ 배열이 없을 λ•ŒκΉŒμ§€ 평탄화

μ˜ˆμ‹œ

const abc = ['a', ['b', 'c', ['d', ['e']]]]

console.log(abc.flat()); // ['a', 'b', 'c', ['d', ['e']]]
console.log(abc.flat(2)); // ['a', 'b', 'c', 'd', ['e']]
console.log(abc.flat(Infinity)); // ['a', 'b', 'c', 'd', 'e']

flatMap()

μ„€λͺ…

πŸ’‘ μ£Όμ–΄μ§„ λ°°μ—΄μ˜ 각 μš”μ†Œμ— λŒ€ν•΄ μž‘μ„±λœ 콜백 ν•¨μˆ˜λ₯Ό μ‹€ν–‰ ν›„ ν•΄λ‹Ή 콜백 ν•¨μˆ˜μ˜ 리턴값을 ν‰λ©΄ν™”ν•˜μ—¬ 단일 μˆ˜μ€€μ˜ μƒˆλ‘œμš΄ 배열을 μƒμ„±ν•˜λŠ” ν•¨μˆ˜

μ‚¬μš©λ²•

array.flatMap(callback[, thisArg])
// arr : 원본 λ°°μ—΄
// callback (ν•„μˆ˜) : 원본 λ°°μ—΄μ˜ 각 μš”μ†Œμ— λŒ€ν•΄ μ‹€ν–‰ν•  콜백 ν•¨μˆ˜μ΄λ©° μš”μ†Œ, 인덱슀, λ°°μ—΄ 전체λ₯Ό λ§€κ°œλ³€μˆ˜λ‘œ λ°›μŒ
// thisArg (선택) : 콜백 ν•¨μˆ˜ λ‚΄μ—μ„œ μ‚¬μš©ν•  this κ°’, 콜백 ν•¨μˆ˜μ˜ this κ°’ μ§€μ • κ°€λŠ₯
// λ°°μ—΄μ˜ μ΅œλŒ€ 깊이 1만큼만 평탄화 κ°€λŠ₯

μ˜ˆμ‹œ

const arr = [1, 2, 3];

/* map() */
const mapArr = arr.map((num) => [num, num * 2]);
console.log(mapArr); // map 리턴값 : [[1, 2], [2, 4], [3, 6]]

/* flatMap() */
const flatMapArr = arr.flatMap((num) => [num, num * 2]);
// === arr.map((num) => [num, num * 2]).flat();
console.log(flatMapArr); // flatMap 리턴값 : [1, 2, 2, 4, 3, 6]

비ꡐ

ν•¨μˆ˜ 리턴값
map() μ½œλ°±ν•¨μˆ˜μ˜ 결과값이 μ •μ§ν•˜κ²Œ 리턴
flatMap() 단일 ꡬ쑰의 λ°°μ—΄μ΄λ‚˜ 객체λ₯Ό 리턴
λ°˜μ‘ν˜•