javascript

map() forEach()

IC 2023. 3. 5.

배열을 순회하는 방법

✅ Array 관련 메소드

👉 map()과 forEach() 모두 Array 관련 메서드들로써, ES5 부터 등장하였다.
👉 forEach()는 배열 요소마다 한 번씩 주어진 함수(콜백)를 실행.
👉 map()은 배열 내의 모든 요소 각각에 대하여 주어진 함수(콜백)를 호출한 결과를 모아 새로운 배열을 반환.
👉 map()과 forEach() 모두 아래 3 개의 인자로 호출됨

  • currentValue (배열 원소의 값)
  • index (현재 요소의 인덱스)
  • array (현재 배열)

 요약

forEach()
: Array 배열 요소를 제공된 함수로 한 번 실행(배열의 각 요소에 대해 callback을 실행).

forEach() 메소드는 아무것도 리턴하지 않는다(undefined).
단지 제공된 함수로 Array 요소를 순회한 후 호출만 한다.

이 콜백은 호출하는 Array를 변경할 수 있다.(원래의 Array에 영향을주고 변경)

const animals = ["lion", "tiger"];
animals.forEach(animal => {
  console.log(animal);
});
// [콘솔 출력 결과]
// lion
// tiger
// ❗ forEach 메소드는 return이 없다(순회한 후 호출만 한다).

map()
: 모든 Array 요소가 제공된 함수로 호출될때 새로운 array를 생성
(배열의 각 요소에 대해 callback을 실행하고 실행결과를 모은 새 배열을 리턴).

map() 메소드는 Array안에 요소들을 호출한다.
forEach()와 다른점은 값을 사용하고 Array와 동일한 사이즈의 새로운 Array을 반환한다.(원래 배열은 변경되지 않는다)

/* return이 없는 map()메소드 */
const animals = ["lion", "tiger"];
let rr = animals.map(animal => {
  console.log(animal);
});

console.log(rr); // [undefined, undefined]
// [콘솔 출력 결과]
// [undefined, undefined]

// ❗ map 메소드를 잘 살리려면 return이 있어야 한다.


/* return이 있는 map()메소드 (1) */

const animals = ["lion", "tiger"];
let rr = animals.map(animal => {
  console.log(animal);
  return "mammal " + animal
});
console.log(rr); // ["mammal lion", "mammal tiger"]
// [콘솔 출력 결과]
// ["mammal lion", "mammal tiger"]
// ❗ return을 통해 새로운 배열을 만들어서 출력할 수 있다


/* return이 있는 map()메소드 (2) */

let Array = [
	     {key:1, value:10},
             {key:2, value:20},
             {key:3, value: 30}
             ];

let result = Array.map(function(arr){ 
   let obj = {};
   obj[arr.key] = arr.value;
   return obj;
});
// result는 [{1:10}, {2:20}, {3:30}]
// ❗ new Object에 키값으로 주기 위한 방법 : obj[지정할 key값] = 그에 맞는 value값

✨ 배열을 순회하려면 forEach( ), 배열을 순회 후 새 배열을 얻고 싶다면 map( ) 사용할 것을 권

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

// forEach 함수 사용
arr.forEach((num, index) => {
  return (arr[index] = num * 2);
});
// arr = [2, 4, 6, 8, 10] 


// map 함수 사용
let double = arr.map(num => {
  return num * 2;
});
// doubled = [2, 4, 6, 8, 10]
// Example of forEach()
const arr = [1, 2, 3, 4, 5];
const mulArr = [];

arr.forEach(num => {
  mulArr.push(num * 3);
});
// ❗  .forEach()는 결과로 array를 가지기 위해서 push를 통해 배열을 만들어줘야함

console.log(mulArr); // [3, 6, 9, 12, 15]

// Example of map()
const arr = [1, 2, 3, 4, 5];
const mulArr = arr.map(num => num * 3);

console.log(mulArr); // [3, 6, 9, 12, 15]

✅ 그 외 메소드

👉 find()

배열에서 하나의 요소를 선택할 때 사용한다. 이 메소드는 특정한 조건을 확인하는 함수를 인자로 받아, 조건을 만족하는 맨 처음 요소를 반환한다.
따라서, 인자에 넘겨지는 함수는 true 혹은 false 를 반환하여야 한다.

const inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
];

function isCherries(fruit) { 
  return fruit.name === 'cherries';
}

console.log(inventory.find(isCherries)); 
// { name: 'cherries', quantity: 5 }

👉 filter()

배열에서 특정조건에 해당하는 여러 요소를 선택할때 사용한다. find 메소드와 동일하게 boolean 값을 반환하는 함수를 인자로 받는다.

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

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

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

👉 reduce()

배열의 각 요소에 대해 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과값을 반환.
리듀서 함수는 네 개의 인자를 가진다.

  • 누산기accumulator (acc) : 콜백의 반환값을 누적
  • 현재 값 (cur) : 처리할 현재 요소
  • 현재 인덱스 (idx)
  • 원본 배열 (src)
let total = [ 0, 1, 2, 3 ].reduce(
  ( accumulator, currentValue ) => accumulator + currentValue,
  0
);
// ❗ 0은 초기값 설정. 초기값을 표기해주지 않으면 index 1 부터 콜백 함수를 실행하고 첫 번째 인덱스는 건너 뛴다.
// 예시(1)
const arr1 = [ 1, 2, 3, 4, 5 ];
arr1.reduce((a, b) => a + b); // 15

// 예시(2)
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

console.log(array1.reduce(reducer));
// 10 출력 (1 + 2 + 3 + 4)

console.log(array1.reduce(reducer, 5));
// 15 출력 (5 + 1 + 2 + 3 + 4)

 요약
1. 반환값 없이 각 요소 값에 대해서 일련의 action을 취하려면 forEach
2. 새로운 배열을 생성하려면 map
3. 하나의 결과 값을 반환하려면 reduce
4. 하나의 요소를 선택하려면, find
5. 특정 조건을 만족하는 여러개의 요소를 선택하려면 filter

댓글