๐Ÿ” [์ง๋ฌด ๊ด€๋ จ ์งˆ๋ฌธ] - 12. REST API๋กœ ๋ฐ›์€ ๊ฐ์ฒด์™€ ๋ฐฐ์—ด์€ ๋ณดํ†ต ์–ด๋–ค ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ API๋‚˜ ๋กœ์ง์„ ์ด์šฉํ•ด์„œ ํ™”๋ฉด์— ๋งž๊ฒŒ ๊ฐ€๊ณต์„ ํ•˜๋Š”์ง€?

์กฐ์ค€ํ˜•ยท2021๋…„ 6์›” 29์ผ
0

interview

๋ชฉ๋ก ๋ณด๊ธฐ
18/20
post-thumbnail
  • map, filter, reduce API ์‚ฌ์šฉ ๊ฒฝํ—˜๊ณผ ๊ฐ๊ฐ ์„ค๋ช…

๐Ÿ’ฌ Answer

๐ŸŒ Map, filter, reduce

๐Ÿ‘‰ 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]

map1์ด x => x * 2 ์ด ์‹์œผ๋กœ ๊ณ„์‚ฐ๋œ ์ƒˆ๋กœ์šด ๋ฐฐ์—ด๋กœ ๋ฐ˜ํ™˜๋ฉ๋‹ˆ๋‹ค.

์š”์†Œ๋“ค์—๊ฒŒ ์ผ๊ด„์ ์œผ๋กœ ํ•จ์ˆ˜๋ฅผ ์ ์šฉํ•˜๊ณ  ์‹ถ์„ ๋•Œ ์‚ฌ์šฉํ•˜๊ธฐ ์ ํ•ฉ.

๐Ÿ‘‰ filter()

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"]

result๋Š” ๊ธธ์ด๊ฐ€ 6์ด์ƒ์ธ ๋‹จ์–ด๋“ค๋งŒ ๋ชจ์•„ ์ƒˆ๋กœ์šด ๋ฐฐ์—ด๋กœ ๋ฐ˜ํ™˜๋ฉ๋‹ˆ๋‹ค.

์˜ค์ง booleanํƒ€์ž…๋งŒ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
๋ฆฌํ„ด ๊ฐ’์ด true์ธ ๊ฒฝ์šฐ์—๋งŒ ๋ฐฐ์—ด์— ์ถ”๊ฐ€ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ค‘๋ณต ์ œ๊ฑฐ์ฒ˜๋Ÿผ ์กฐ๊ฑด์— ๋งž๋Š” ํŠน์ • ์š”์†Œ๋“ค๋งŒ ์ƒˆ ๋ฐฐ์—ด์— ๋„ฃ๊ณ  ์‹ถ์€ ๊ฒฝ์šฐ ์‚ฌ์šฉ์— ์ ํ•ฉ.

๐Ÿ‘‰ reduce()

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

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

map, filter๊ฐ™์€ ํ•จ์ˆ˜ํ˜• ๋ฉ”์„œ๋“œ๋ฅผ reduce๋งŒ์œผ๋กœ๋„ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

๐Ÿ“˜ ์ฐธ๊ณ 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
https://velog.io/@tjdud0123/javascript-map-filter-ํ•จ์ˆ˜
https://brunch.co.kr/@swimjiy/15

profile
๊นƒํ—ˆ๋ธŒ : github.com/JuneHyung

0๊ฐœ์˜ ๋Œ“๊ธ€