๐๏ธFrontend/๐จHTML,CSS,JS
[JS] array์ ๋งค์๋(forEach, map, filter, reduce)
bananackck
2025. 2. 24. 18:14
JavaScript์ array ๋ฉ์๋์ ๋ํด ์์๋ณด์. ๋๋ถ๋ถ ํ์์ ํ์ํ ๋ฉ์๋์ด๋ค.
๋ชจ๋ ํ๋ผ๋ฏธํฐ๋ก ์ฝ๋ฐฑํจ์๊ฐ ๋ค์ด๊ฐ๋ค.
forEach
for๋ฌธ๊ณผ ๊ฐ์ ์ญํ . ๋จ์ ์ํ์ ์ ํฉํ๋ค.
const array = [1, 2, 3];
array.forEach((item) => {
console.log(item);
});
// 1
// 2
// 3
map
์๋ก์ด ๋ฆฌ์คํธ๋ฅผ ๋ฐํํ๋ค. ๋ฐฐ์ด ์์์ ๊ฐ์ ๋ฐ๊พธ๊ณ ์ถ์ ๋ ์ ํฉํ๋ค.
let array = [1, 2, 3];
let doubleArray = array.map((item) => {
return item * 2;
});
console.log(doubleArray);
//[2, 4, 6]
filter
๋ฐฐ์ด์ ์์ ์ค ์กฐ๊ฑด์ ๋ง์กฑํ๋ ์์๋ค๋ง ํํฐ๋ง ํด ๋ฆฌ์คํธ๋ก ๋ฐํํ๋ค.
- return ๊ฐ์ true/false๋ก ํ๋ณ๋๊ณ , true์ธ ๊ฐ๋ง ๋ฆฌ์คํธ์ ๋ค์ด๊ฐ ๋ฐํ๋๋ค.
let array = [1, 2, 3];
let odd = array.filter((item) => {
return item % 2;
});
console.log(even);
// [1, 3]
reduce
๋ฐฐ์ด์ ์์๋ฅผ ์ผ์ชฝ๋ถํฐ ์ํํ๋ฉด์ ๋ฐ๋ณต์ ์ธ ์ฐ์ฐ์ ํ๋ ๋ฉ์๋์ด๋ค.
๋ ๊ฐ์ ํ๋ผ๋ฏธํฐ๋ฅผ ๊ฐ์ง๋ค.
๋ฐฐ์ด.reduce((๊ฒฐ๊ณผ ๋ณ์, ํ์ฌ ์์, ํ์ฌ ์์ index, ํ์ฌ ๋ฐฐ์ด)=>{return ;}, ์ด๊ธฐ ๊ฐ)
- ์ฝ๋ฐฑํจ์
- ๊ฒฐ๊ณผ ๋ณ์ : ์ฝ๋ฐฑ ํจ์์ ๋ฆฌํด ๊ฐ์ด ์ด ์ฒซ๋ฒ์งธ ํ๋ผ๋ฏธํฐ๋ก ์ ๋ฌ๋๋ค. (๋์ ๋๋ค.)
- ํ์ฌ ์์ : ํ์ฌ ํ์ํ๊ณ ์๋ ๋ฐฐ์ด์ ์์
- ํ์ฌ ์์ index : ํ์ฌ ํ์ํ๊ณ ์๋ ๋ฐฐ์ด์ ์์์ ์ธ๋ฑ์ค (์๋ต ๊ฐ๋ฅ)
- ํ์ฌ ๋ฐฐ์ด : ํ์ฌ ํ์ํ๊ณ ์๋ ๋ฐฐ์ด (์๋ต ๊ฐ๋ฅ)
- ์ด๊ธฐ ๊ฐ : ๊ฒฐ๊ณผ ๋ณ์์ ์ด๊ธฐ ๊ฐ์ ์ง์ ํ๋ค. ์๋ต๋๋ฉด ๋ฐฐ์ด์ ์ฒซ ๋ฒ์งธ ์์๋ก ์ด๊ธฐํ๋๋ค.
let array = [1, 2, 3];
let cumulativeValue = array.reduce((sum, curr, currIdx, array) => {
return sum + curr;
}, 0);
console.log(cumulativeValue);
// 6
โ ๋ฆฌ์คํธ ์์ ์๋ ์์์ ๊ฐ์๋ฅผ ์ธ์ ๊ฐ์ฒด๋ก ๋ฐํํ๋ ์์ฉ
const fruits = ["Orange", "Orange", "Apple", "Apple", "Pear", "Banana"];
const states = fruits.reduce((box, fruit) => {
return { ...box, [fruit]: (box[fruit] || 0) + 1 };
// Spread Syntax(...) ์ฌ์ฉ : ๊ธฐ์กด ๊ฐ์ฒด(box)์ ๋ด์ฉ์ ๋ณต์ฌํ์ฌ ์๋ก์ด ๊ฐ์ฒด๋ฅผ ์์ฑํจ.
}, {});
console.log(states);
// {Orange: 2, Apple: 2, Pear: 1, Banana: 1}
โ
์ฌ๋ฌ ๋ฐฐ์ด์ ํ๋๋ก ํฉ์น๋ ์์ฉ
const alphabet = [
["a", "b", "c", "d"],
["e", "f", "g"],
["h", "i"],
];
const flattened = alphabet.reduce((sumArr, currArr) => prev.concat(currArr));
console.log(flattened);
// ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
+ reduceRight
๋ฐฐ์ด์ ์์๋ฅผ ์ค๋ฅธ์ชฝ๋ถํฐ ์ํ