javascript๐Ÿ‘ฉโ€๐Ÿ’ป์˜ map(), filter(), reduce()

5320 ๋‹จ์–ด beginnerstutorialjavascriptwebdev
์ด๊ฒƒ๋“ค์€ ๋ชจ๋‘ ๋งค์šฐ ์ค‘์š”ํ•˜๋ฉฐ ํ”„๋กœ์ ํŠธ๋‚˜ ์›น ์‚ฌ์ดํŠธ๋ฅผ ๊ฐœ๋ฐœํ•˜๋Š” ๋™์•ˆ ์ž์ฃผ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค. map(), filter & reduce()๋Š” ๊ณ ์ฐจ ํ•จ์ˆ˜, ์ฆ‰ ๋‚ด๋ถ€์— ๋‹ค๋ฅธ ํ•จ์ˆ˜๊ฐ€ ์žˆ๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค.

1. ์ง€๋„()



๋งต ํ•จ์ˆ˜๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ ๊ฐ ์š”์†Œ์— ๋Œ€ํ•ด ์ฃผ์–ด์ง„ ์ž‘์—…์„ ๋ฐ˜๋ณตํ•˜๊ณ  ์ ์šฉํ•ฉ๋‹ˆ๋‹ค.

arr=[1,2,4,3,5,6]

function checkEven(x){
    return x%2==0;
}
const ans=arr.map(checkEven)
console.log(ans)




์—ฌ๊ธฐ์„œ๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ ์š”์†Œ๊ฐ€ ์ง์ˆ˜์ธ์ง€ ์—ฌ๋ถ€๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ณ  ์กด์žฌํ•˜๋Š” ๊ฐ ์š”์†Œ์˜ ๊ฐ’์„ ์ˆ˜์ •ํ•ฉ๋‹ˆ๋‹ค.

2. ํ•„ํ„ฐ()



์ด ํ•จ์ˆ˜๋Š” ๋ฐฐ์—ด์„ ์‚ฌ์šฉํ•˜์—ฌ ๊ฐ ์š”์†Œ์˜ ์กฐ๊ฑด์„ ํ™•์ธํ•˜๊ณ  ์ž˜๋ชป๋œ ๊ฐ’์„ ํ•„ํ„ฐ๋งํ•ฉ๋‹ˆ๋‹ค.

arr=[1,2,4,3,5,6]

const ans=arr.filter(function checkEven(x){
    return x%2==0;
})
console.log(ans)




์—ฌ๊ธฐ์„œ ๋ชจ๋“  ๊ฑฐ์ง“ ๊ฐ’์ด ์ œ๊ฑฐ๋ฉ๋‹ˆ๋‹ค. ์ด๋Ÿฌํ•œ ํ•จ์ˆ˜๋Š” ๊ธฐ๋ณธ ์–ด๋ ˆ์ดarr์˜ ๋ณ€๊ฒฝ ์‚ฌํ•ญ์„ ๋ฐ˜์˜ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

3. ๊ฐ์†Œ()



์ „์ฒด ๋ฐฐ์—ด์— ๋Œ€ํ•œ ์ž‘์—…์˜ ์ถœ๋ ฅ์„ ๋‹จ์ผ ๋‹ต๋ณ€์œผ๋กœ ์š”์•ฝํ•ฉ๋‹ˆ๋‹ค.

๋ชจ๋“  ๋‹จ๊ณ„์—์„œ ans๋ฅผ ์ถ”์ ํ•˜๋Š” accumulator ๋ฐ current ์š”์†Œ๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. ์—ฌ๊ธฐ์„œ ans๋Š” ๋ˆ„์‚ฐ๊ธฐ์ด๊ณ  x๋Š” ๋ฐฐ์—ด์˜ ํ˜„์žฌ ์š”์†Œ์ž…๋‹ˆ๋‹ค.
},0) ๋ถ€๋ถ„์—์„œ ์ด 0์€ ๋ˆ„์‚ฐ๊ธฐans์˜ ์ดˆ๊ธฐ ๊ฐ’์ž…๋‹ˆ๋‹ค.

arr=[2,4,6,6,8,9,22]

const ans=arr.reduce(function checkMax(ans, x){
    ans=ans>x?ans:x
    return ans;
},0)

console.log(ans)




์—ฌ๊ธฐ์„œ ์šฐ๋ฆฌ๋Š” ์ตœ๋Œ€ ์š”์†Œ๋ฅผ ์ถ”์ ํ•˜๊ณ  ํ˜„์žฌ์™€ ๋น„๊ตํ•˜์—ฌ ์ตœ๋Œ€๋ณด๋‹ค ํฌ๋ฉด ์—…๋ฐ์ดํŠธํ•ฉ๋‹ˆ๋‹ค.

You can even pass arrow functions inside these functions. โญ MDN -Arrow functions

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ