[JS] Map, Filter, Reduce

hye0n.gyu·2024년 7월 21일
0

JS

목록 보기
7/13
post-thumbnail

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

⭐ Filter

filter는 배열의 요소를 순회하면서 콜백 함수를 사용하여 원하는 조건에 따라 필터링하는 함수이다.

const words = ['spray', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter((word) => word.length > 6);

console.log(result);
// Expected output: Array ["exuberant", "destruction", "present"]

⭐ Reduce

reduce는 배열의 모든 요소에 콜백 함수를 적용하여 하나의 결과 값을 생성하는 함수이다.
배열의 요소들을 하나로 줄여(reduce) 집계한 값을 반환한다.

`reduce`는 return된 값을 acc에 넣으며 모든 배열의 값과 acc를 연산하며 누적한다.
아래의 사진을 통해 이해하면 편할 것이다.

Ex1

const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  initialValue,
);

console.log(sumWithInitial);
// Expected output: 10

Ex2

const array1 = [1, 2, 3, 4];

const minValue = array1.reduce((acc, arrNum) => {
	if(acc > arrNum){return arrNum;}
  	else{return acc}
})

✔ 초기값 변경

reduce에 콜백 함수를 넣고 그 다음 인자에 값이나 변수를 넣으면 초기 값이 그 값 또는 변수로 설정된다.

const evens = [2, 4, 6, 8];

evens.reduce((sum, num) => sum + num, 100) // 120
profile
반려묘 하루 velog

0개의 댓글