[JavaScript] 배열(Array)의 내장매서드 forEach, map, filter, find, reduce

iberis2·2023년 1월 12일
0

배열의 매서드

매서드 : 객체의 파라미터로 있는 함수
자바스크립트의 배열에는 기본적으로 내장되어 있는 유용한 고차함수 매서드들이 있다.

💡 공통적인 특징
① 첫 번째 파라미터는 배열의 요소, ② 두 번째 파라미터는 인덱스, ③ 세 번째 파라미터는 배열 자체를 받는다.
(단, reduce는 ③ 세 번째 파라미터가 인덱스, ④ 네 번째 파라미터가 배열 자체이다.)
첫 번째 파라미터만 필수 요소이다. (두 번째 파라미터부터는 생략 가능)
주로 첫 번째 파라미터(배열의 요소)만 사용하고, 두 번째(인덱스), 세 번째(배열 자체)는 거의 사용하지 않는 편이다.

콜백함수 : 함수의 파라미터로 들어가는 함수

forEach

배열.forEach((요소, 인덱스, 배열 자체) => 동작)
배열의 모든 요소를 순회하며 콜백함수를 수행한다.
❗️ 값을 따로 return하지 않아, return 값은 항상 undefined 이다.

const members = ["영지", "민지", "지원", "아영"];

members.forEach(function (member, i) {
  console.log(`${i} ${member}님이 입장하셨습니다.`);
});
/* 0 영훈님이 입장하셨습니다.
1 민지님이 입장하셨습니다.
2 지원님이 입장하셨습니다.
3 아영님이 입장하셨습니다. */

const member = members.forEach((member)=> member);
console.log(member); // undefined

세 번째 파라미터로 배열 그 자체를 불러올 수 있다.

["사과", "바나나", "귤", "복숭아"].forEach((i, o, arr) => console.log(arr));
/*
[ '사과', '바나나', '귤', '복숭아' ]
[ '사과', '바나나', '귤', '복숭아' ]
[ '사과', '바나나', '귤', '복숭아' ]
[ '사과', '바나나', '귤', '복숭아' ]
*/


// 파라미터를 전달하지 않고 그냥 , 쉼표로 두면 SyntaxError가 발생한다.
["사과", "바나나", "귤", "복숭아"].forEach(( ,  , arr) => console.log(arr));
// SyntaxError: Unexpected token ','

Map

배열.map((요소, 인덱스, 배열 자체) => 동작)
배열의 각 요소에 콜백함수를 적용시킨 요소를 가진 새로운 배열을 리턴한다.
💡forEach와 달리 return 값이 있다.
매핑(mapping) : 어떤 값을 다른 값을 가리키도록 하는 것

let arr = [1, 2, 3, 4, 5]
function multiply2(num){
  return num * 2;
}

// 편의상 console.log 생략
arr.map(multiply2); // [2, 4, 6, 8, 10]

// 함수를 바로 넣어서 쓸 수도 있음 
arr.map((el) => el * 2);  // [2, 4, 6, 8, 10]

최대 반복 회수는 처음 호출할 때의 배열 요소의 개수이다.
중간에 배열의 요소를 추가해도 반복회수가 늘어나지 않고, 무한루프에 빠지지 않는다.

const myNum = [1, 2, 3, 4, 5];

myNum.forEach((num, i) => {
  console.log(`현재 ${num}일 때 ${i} 추가`);
  myNum.push(i); // 반복할 때마다 요소를 추가해도 무한루프에 빠지지 않는다.
  return num;
});
/*
현재 1일 때 0 추가
현재 2일 때 1 추가
현재 3일 때 2 추가
현재 4일 때 3 추가
현재 5일 때 4 추가
*/

console.log(myNum); //[ 1, 2, 3, 4, 5, 0, 1, 2, 3, 4 ]

하지만 반복하며 배열의 요소가 줄어들 경우, 반복 횟수도 줄어든다.

const myNum = [1, 2, 3, 4, 5];

myNum.forEach((num) => {
  console.log(num);
  myNum.pop();
}); // 1, 2, 3

filter

배열.filter((요소, 인덱스, 배열) => 동작);

배열의 각 요소에 콜백 함수를 적용시켰을 때, true를 리턴하는 요소들만 모은 새로운 배열을 리턴한다.

const devices = [
  { name: "GalaxyNote", brand: "Samsung" },
  { name: "MacbookPro", brand: "Apple" },
  { name: "iPad", brand: "Apple" },
  { name: "GalaxyWatch", brand: "Samsung" },
  { name: "Gram", brand: "LG" },
  { name: "MacbookAir", brand: "Apple" },
];

const samsung = devices.filter((el) => el.brand === "Samsung");
console.log(samsung);
//[{ name: 'GalaxyNote', brand: 'Samsung' }, { name: 'GalaxyWatch', brand: 'Samsung' }]

const LG_LAPTOP = devices.filter((el) => el.brand === "LG");
//배열로 반환해주기 때문에, 요소만 필요할 경우 sprad 구문으로 풀어줘야함
console.log(...LG_LAPTOP); // { name: 'Gram', brand: 'LG' }

요소의 개수만큼 전부 반복함

const how_many_turn_filter = devices.filter((el, i) => {
  console.log(i);
  return el.brand === "Apple";
}); //0 1 2 3 4 5

console.log(how_many_turn_filter); // [  { name: 'MacbookPro', brand: 'Apple' },  { name: 'iPad', brand: 'Apple' },  { name: 'MacbookAir', brand: 'Apple' }]

find

배열.find((요소, 인덱스, 배열) => 동작)
배열의 각 요소에 콜백 함수를 적용시켰을 때, true를 리턴하는 최초의 값을 리턴한다.

const devices = [
  { name: "GalaxyNote", brand: "Samsung" },
  { name: "MacbookPro", brand: "Apple" },
  { name: "iPad", brand: "Apple" },
  { name: "GalaxyWatch", brand: "Samsung" },
  { name: "Gram", brand: "LG" },
  { name: "MacbookAir", brand: "Apple" },
];

const LG_Notebook = devices.find((el) => el.brand === "LG");
console.log(LG_Notebook); // { name: 'Gram', brand: 'LG' }

// find는 일치하는 하나의 값만 찾으면 반복을 종료함
const Apple_Item = devices.find((el) => el.brand === "Apple");
console.log(Apple_Item);  // { name: 'MacbookPro', brand: 'Apple' }

find는 일치하는 값을 찾을 때 까지만 반복함


const how_many_turn_find = devices.find((el, i) => {
  console.log(i);
  return el.brand === "Apple";
}); // 0, 1
console.log(how_many_turn_find);  // { name: 'MacbookPro', brand: 'Apple' }

reduce

배열.reduce((누적된 값, 현재 요소, 인덱스, 배열) => {return 계산식}, 최초 값)
배열의 각 요소를 콜백 함수에 맞게 하나로 응축시킨 값을 리턴한다.

let numbers = [1, 2, 3, 4, 5];

const sumNumbers = numbers.reduce((acc, el, i) => {
  console.log(`${i}번째 index 요소`);
  console.log(`acc: ${acc}`);
  console.log(`el: ${el}`);
  console.log(`-----------`);
  return acc + el;
}, 0);

/*
0번째 index 요소
acc: 0
el: 1
-----------
1번째 index 요소
acc: 1
el: 2
-----------
2번째 index 요소
acc: 3
el: 3
-----------
3번째 index 요소
acc: 6
el: 4
----------- 
4번째 index 요소
acc: 10
el: 5
-----------*/

console.log(sumNumbers); // 15

초기값을 설정하지 않으면 배열의 첫 번째 요소첫 번째 파라미터, 두 번째 요소가 두번째 파라미터로 시작한다.

let numbers = [1, 2, 3, 4, 5];

const sumNumbers = numbers.reduce((acc, el, i) => {
  console.log(`${i}번째 index 요소`);
  console.log(`acc: ${acc}`);
  console.log(`el: ${el}`);
  console.log(`-----------`);
  return acc + el;
});
/*
1번째 index 요소
acc: 1
el: 2
-----------
2번째 index 요소
acc: 3
el: 3
-----------
3번째 index 요소
acc: 6
el: 4
-----------
4번째 index 요소
acc: 10
el: 5
-----------
*/

console.log(sumNumbers); // 15
profile
React, Next.js, TypeScript 로 개발 중인 프론트엔드 개발자

0개의 댓글