JS Map/Filter/Reduce

Calvin Park·2022년 6월 26일
0

Map은 forEach와 비슷하다고 생각하면 된다. 단 결과는 배열로 나온다

map -> Create a new Array by doing something with each items in an array.
i.e 배열안에 있는 아이템들을 가지고 doing something을 한다음 새로운 배열을 생성한다.

e.g.

const numbers = [3, 56, 2, 48, 5]
function double(x){
return x * 2;
}
const actions = numbers.map(double);
numbers 배열에 있는 것이 2씩 곱해서 새로운 배열을 생성한다.

하지만 forEach 문은 새로운 배열로 만들어서 나오지는 안는다. forEach문을 해서 배열을 생성 하고 싶으면
let nuwNumbers = [];
function dobule(x){
	newNumbers.push(x * 2);
}
numbers.forEach(dobule);
console.log(newNumbers) -> 값은 상위 map 한것과 동일하다.

p.s 간략하게 사용하는 방법은 let newNumbers = numbers.map((x) => {
	return x * 2;
})
상위 map과 같은 결과이다.

Filter는 값이 true인것만 담아서 새로운 배열로 만든다.

Filter -> Create a new array by keeping the items that return true
e.g.

const numbers = [3, 56, 2, 48, 5]
const newNumbers1 = numbers.filter((num) => {
	return num > 10;
})
출력: [56, 58]
true인 item(s)가 return 후 created new Array 가된다. 
comparing to create new Array using forEach

let newNumbers2 = []; //배열을 만든다
numbers.forEach((num) => {    //forEach 사용
	if(num > numbers){			  //if 문을 통하여 true인 item(s)만 push 한다.
    	newNumbers2.push(num);
    };
});
출력: 상위 와 같다.
p.s. filter를 사용하는것이 훨신 더 간략하다. 

Reduce는 값을 더한다.

Reduce -> Accumulate a value by doing something to each item in an array.

일단 보자

forEach문을 예로 들자.
const numbers = [3, 56, 2, 48, 5];
var add = 0;
numbers.forEach((num) => {
	add += num;
})
출력: 114 numbers 배열안에 있는 items를 더한다.

BUT reduce를 사용하면
const action = numbers.reduce((accumulator, currentNumber) => {
	return accumulator + currentNumber;
})
출력: 114

훨씬 간단하게 만들수 있다. 
중요한것은 accumulator 와 currentNumber이다. 매개변수는 필이다.
accumulator는 누적된 값이라는 뜻이다. 

잘만사용하면 유용하다.

profile
Personal Velog Note

0개의 댓글