DevLog

๊ณ ์ฐจํ•จ์ˆ˜ ๋ฉ”์„œ๋“œ ์ •๋ฆฌ(map, filter, reduce) ๋ณธ๋ฌธ

๐Ÿง‘๐Ÿป‍๐Ÿ’ป ๊ฐœ๋ฐœ๊ฐœ๋ฐœ/javascript

๊ณ ์ฐจํ•จ์ˆ˜ ๋ฉ”์„œ๋“œ ์ •๋ฆฌ(map, filter, reduce)

Seungjae Lee 2021. 6. 3. 22:34

map()

map() ๋ฉ”์„œ๋“œ๋Š” ๋ฐฐ์—ด ๋‚ด์˜ ๋ชจ๋“  ์š”์†Œ ๊ฐ๊ฐ์— ๋Œ€ํ•˜์—ฌ ์ฃผ์–ด์ง„ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•œ ๊ฒฐ๊ณผ๋ฅผ ๋ชจ์•„ ์ƒˆ๋กœ์šด ๋ฐฐ์—ด์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

map ํ™œ์šฉ ์‹œ, ์•„๋ž˜ ๊ณผ์ •์„ ๊ผญ ๊ธฐ์–ตํ•˜์„ธ์š”.

  • ๋ฐฐ์—ด์˜ ๊ฐ ์š”์†Œ๊ฐ€
  • ํŠน์ • ๋…ผ๋ฆฌ(ํ•จ์ˆ˜)์— ์˜ํ•ด
  • ๋‹ค๋ฅธ ์š”์†Œ๋กœ ์ง€์ •(map) ํ•ฉ๋‹ˆ๋‹ค.
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]

 

filter()

filter() ๋ฉ”์„œ๋“œ๋Š” ์ฃผ์–ด์ง„ ํ•จ์ˆ˜์˜ ํ…Œ์ŠคํŠธ๋ฅผ ํ†ต๊ณผํ•˜๋Š” ๋ชจ๋“  ์š”์†Œ๋ฅผ ๋ชจ์•„ ์ƒˆ๋กœ์šด ๋ฐฐ์—ด๋กœ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

filter ํ™œ์šฉ ์‹œ, ์•„๋ž˜ ๊ณผ์ •์„ ๊ผญ ๊ธฐ์–ตํ•˜์„ธ์š”.

  • ๋ฐฐ์—ด์˜ ๊ฐ ์š”์†Œ๊ฐ€
  • ํŠน์ • ๋…ผ๋ฆฌ(ํ•จ์ˆ˜)์— ๋”ฐ๋ฅด๋ฉด, ์‚ฌ์‹ค(boolean)์ผ ๋•Œ
  • ๋”ฐ๋กœ ๋ถ„๋ฅ˜ํ•ฉ๋‹ˆ๋‹ค(filter).
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

 

reduce() 

reduce() ๋ฉ”์„œ๋“œ๋Š” ๋ฐฐ์—ด์˜ ๊ฐ ์š”์†Œ์— ๋Œ€ํ•ด ์ฃผ์–ด์ง„ ๋ฆฌ๋“€์„œ(reducer) ํ•จ์ˆ˜๋ฅผ ์‹คํ–‰ํ•˜๊ณ ,
ํ•˜๋‚˜์˜ ๊ฒฐ๊ณผ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.reduce ํ™œ์šฉ ์‹œ, ์•„๋ž˜ ๊ณผ์ •์„ ๊ผญ ๊ธฐ์–ตํ•˜์„ธ์š”.

  • ๋ฐฐ์—ด์˜ ๊ฐ ์š”์†Œ๋ฅผ
  • ํŠน์ • ๋ฐฉ๋ฒ•(ํ•จ์ˆ˜)์— ๋”ฐ๋ผ
  • ์›ํ•˜๋Š” ํ•˜๋‚˜์˜ ํ˜•ํƒœ๋กœ
  • ์‘์ถ•ํ•ฉ๋‹ˆ๋‹ค. (reduction)
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

๋ฆฌ๋“€์„œ ํ•จ์ˆ˜๋Š” ๋„ค ๊ฐœ์˜ ์ธ์ž๋ฅผ ๊ฐ€์ง‘๋‹ˆ๋‹ค.

  1. ๋ˆ„์‚ฐ๊ธฐaccumulator (acc)
  2. ํ˜„์žฌ ๊ฐ’ (cur)
  3. ํ˜„์žฌ ์ธ๋ฑ์Šค (idx)
  4. ์›๋ณธ ๋ฐฐ์—ด (src)

๋ฆฌ๋“€์„œ ํ•จ์ˆ˜์˜ ๋ฐ˜ํ™˜ ๊ฐ’์€ ๋ˆ„์‚ฐ๊ธฐ์— ํ• ๋‹น๋˜๊ณ , ๋ˆ„์‚ฐ๊ธฐ๋Š” ์ˆœํšŒ ์ค‘ ์œ ์ง€๋˜๋ฏ€๋กœ ๊ฒฐ๊ตญ ์ตœ์ข… ๊ฒฐ๊ณผ๋Š” ํ•˜๋‚˜์˜ ๊ฐ’์ด ๋ฉ๋‹ˆ๋‹ค.

 arr.reduce(callback[, initialValue]) 

- callback : ๋ฐฐ์—ด์˜ ๊ฐ ์š”์†Œ์— ๋Œ€ํ•ด ์‹คํ–‰ํ•  ํ•จ์ˆ˜. ๋‹ค์Œ ๋„ค ๊ฐ€์ง€ ์ธ์ˆ˜๋ฅผ ๋ฐ›์Šต๋‹ˆ๋‹ค.(acc, cur, idx, src)
-initialValue [Optional] : callback์˜ ์ตœ์ดˆ ํ˜ธ์ถœ์—์„œ ์ฒซ ๋ฒˆ์งธ ์ธ์ˆ˜์— ์ œ๊ณตํ•˜๋Š” ๊ฐ’. ์ดˆ๊ธฐ๊ฐ’์„ ์ œ๊ณตํ•˜์ง€ ์•Š์œผ๋ฉด ๋ฐฐ์—ด์˜ ์ฒซ ๋ฒˆ์งธ ์š”์†Œ๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. ๋นˆ ๋ฐฐ์—ด์—์„œ ์ดˆ๊ธฐ๊ฐ’ ์—†์ด reduce()๋ฅผ ํ˜ธ์ถœํ•˜๋ฉด ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•ฉ๋‹ˆ๋‹ค.

Comments