์ฒ์์๋ array๋ฅผ ์ฌ์ฉํ์ง ๋ง๋ผ๊ณ ํด์ ๋นํฉ์ค๋ฝ๊ณ ์ด๋ ค์ ๋๋ฐ, ํด๊ฒฐ๋ฐฉ์์ ์ฐพ๊ณ ๋๋ ์๊ฐ๋ณด๋ค ์์ํ๊ฒ ํด๊ฒฐ๋์๋ค.
๋ถ๋ณ์ฑ Immutable
์ฌ๋ณผ์ ๊ฐ์ด ๋ณ๊ฒฝ๋์ง ์๋๋ค์์ํจ์ pure function
์์ ํจ์**๋ผ๊ณ ๋ถ๋ฆ์ฐธ์กฐํฌ๋ช ์ฑ๊ณผ ๋ถ์์ฉ
๊ณ ์ฐจํจ์
map
const numberArr = [1, 2, 3, 4, 5];
const numberMapArr = numberArr.map((item) => {
return (item % 2 === 0) ? 'even' : 'odd'; // ์ฐ์ฐํ ๊ฒฐ๊ณผ๊ฐ์ ๋ฃ์ด ๋ฐฐ์ด ๋ฐํ
});
console.log(numberMapArr); // ['odd', 'even', 'odd', 'even', 'odd']
findIndex
const objectArr = [
{ name: 'Harry', age: 20 },
{ name: 'Kim', age: 30 },
{ name: 'Steve', age: 40 }
];
console.log(objectArr.findIndex(item => {
return item.age === 20 // ํด๋น์กฐ๊ฑด์ ๋ถํฉํ๋ฉด item์ ์ธ๋ฑ์ค๋ฅผ ๋ฐํ
}); // 0
console.log(objectArr.findIndex(item => item.name === 'Kim')); // 1
.filter()
const numberArr = [1, 2, 3, 4, 5];
const numberFilterArr = numberArr.filter((item) => {
return item % 2 === 0; // ํด๋น์กฐ๊ฑด์ ๋ถํฉ์ผ๋ฉด item์ ๋ฃ์ด ๋ฐฐ์ด ๋ฐํ
});
console.log(numberFilterArr); // [2, 4]
reduce
const numberArr = [1, 2, 3, 4, 5];
const sum = numberArr.reduce((previousValue, currentValue, currentIndex, thisArray) => {
console.log('Current Index: ' + currentIndex + ' / Previous Value: ' + previousValue + ' / Current Value: ' + currentValue);
return previousValue + currentValue; // ์ฐ์ฐํ ๊ฒฐ๊ณผ๊ฐ์ ๋์ฐ๊ธฐpreviousValue์ ๋ฃ์ด ์ต์ข
๊ฐ์ ์ป๋๋ค.
}, 0);
console.log('Sum: ' + sum);
ํด๋ก์ ธ ๋ฐ ํจ์ ๋ฒ์ (์ค์ฝํ)
๊ณ ์ฐจํจ์์ ์ปค๋ง ๋ฐฉ์
๊ฐ์ฒด ์งํฅ vs ํจ์์งํฅ