🗺 Map 메소드

배열 내의 모든 요소 각각에 대해
주어진 함수를 호출한 결과를 모아 새로운 배열을 반환🔁

const array1 = [1, 4, 9, 16];

const map1 = array1.map(x => x * 2);
// 각각 2를 곱한 새로운 배열 [2, 8, 18, 32] 출력
console.log(map1); 

새로운 배열이란 건 array1 업데이트한다는걸까❓➡❌
기존 배열 건들지 않고 완전 새로운 배열을 만드는 것

✔ 완전 새로 만들기 때문에 불변성(immutability) 지키기도 좋음

...

array.map(function(item, index, array) {
  // return 새로 만들 값
});

🔹 item : 현재 요소, index : 현재 요소의 인덱스, array : 원본 배열 전체

const fruits = ['apple', 'banana', 'cherry'];

const newFruits = fruits.map(function(item, index, array) {
  return `${index + 1}. ${item.toUpperCase()} (총 ${array.length}개)`;
});

console.log(newFruits);
[
  "1. APPLE (총 3개)",
  "2. BANANA (총 3개)",
  "3. CHERRY (총 3개)"
]

💧 filter 메소드

👉 조건을 만족하는 요소만 골라 새로운 배열을 만드는 메서드

const words = ['spray', 'limit', 'elite', 'destruction'];
// 길이 5 -> spray, limit, elite라 false고 destruction 얘만 true
const result = words.filter(words => word.length > 6);

console.log(result); // 출력 : ['destruction']

...

const words = ["apple", "bnana", "cherry", "date", "agg"];

const filter = words.filter((word, index, array) => {
  console.log("단어:", word, "인덱스", index, "전체배열", array);
  return word.length > 4;  // 길이가 5이상인 것만 출력
});

console.log(filtered); // ["apple", "banana", "cherry"]
  • word → 현재 요소 ( "apple" 등 )
  • index → 현재 요소의 인덱스 ( 0, 1, 2… )
  • array → 전체 배열 (["apple", "banana", "cherry", "date", "egg"])
  • return word.length > 4 → 글자 수가 4보다 큰 단어만 새 배열에 담음

✨reduce 메소드

배열의 각 요소에 대해 주어진 리듀서 함수를 실행하고
하나의 결괏값을 반환🔁

4️⃣개의 인자를 가짐

  • 누산기 (acc) : 이전 반복에서 반환된 값을 누적해 저장하는 변수
  • 현재 값 (cur) : 현재 순회 중인 배열 요소
  • 현재 인덱스 (idx) : 현재 요소의 위치(인덱스)
  • 원본 배열 (src) : reduce가 실행되는 전체 배열

현재 여기선 reducer 함수만 있고 initialValue는 안 사용함

🔻initialValue➡reduce( ) 함수에서 누산기(acc)의 초기값
👉 처음 시작할 때 acc에 넣어줄 값

profile
안녕하세요! 퍼블리싱 & 프론트엔드 개발 공부 블로그 입니다!

0개의 댓글