TIL 003 | JavaScript Array.prototype.map()

This Is Empty.·2021년 8월 5일
0

TIL

목록 보기
3/23
post-thumbnail

❓ map() 메서드를 사용하는 이유

  • 코드 입력의 양을 크게 줄일 수 있다.
  • 코드의 가독성이 올라간다.
  • 기존 배열을 유지하기때문에 코드를 이해하기 쉽다.

Array.prototype.map()

1. 사용 방법

map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 콜백함수를 호출한 결과를 모아 새로운 배열을 반환한다. 각 요소들에 대해 콜백함수를 모두 호출하고 나면 값이 바뀐 배열을 리턴한다. 기존의 배열은 그대로 존재한다.

let originalArray = [1,2,3,4,5];
let newArray = originalArray.map(function addOne(num) {
  return num + 1; 
});

console.log(originalArray); // output : [1,2,3,4,5]
console.log(newArray); // output : [2,3,4,5,6]

익명함수도 사용 가능하다

let originalArray = [1,2,3,4,5];
let newArray = originalArray.map(function(num) {
  return num + 1;
});

console.log(originalArray); // output : [1,2,3,4,5]
console.log(newArray); // output : [2,3,4,5,6]

콜백 함수를 독립형 함수로 쓰려면 map메서드에 전달하기 위해 변수 이름을 지정해야 한다.

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

function addOne (num) {
  return num +1; 
}

let newArray = originalArray.map(addOne);

console.log(originalArray); // output : [1,2,3,4,5]
console.log(newArray); // output : [2,3,4,5,6]

람다(화살표 함수)를 사용할 수 있다.

let originalArray = [1,2,3,4,5];
let newArray = originalArray.map(num => num+1);

console.log(originalArray); // output : [1,2,3,4,5]
console.log(newArray); // output : [2,3,4,5,6]

2. 작동 방식

Map 메서드의 콜백함수는 다음의 세가지의 인수를 사용하지만, 모두 필요한 것은 아니다.

array.map((value, index, array) => { ... });

value : 기존 배열의 값
index : 현재 처리중인 항목의 인덱스
array : 원래 호출 된 배열, 자주 사용하지 않는다(배열을 변수에 이미 연결한 경우 map이 원래 호출된 배열에 대한 참조가 있기 때문이다)

let myArray = [1,2,3];

// 세번째 인수를 사용하여 매핑
myArray.map((value, index, array) => {
  return array[index] + 1;
});

// 원래 배열을 보유하는 변수를 사용
myArray.map((value, index) => {
  return myArray[index] + 1;
});

// 수동으로 배열에 접근하지 않고 map만 사용
myArray.map((value) => {
  return value +1;
});

3. 복잡한 데이터에 map을 사용하는 방법

1. map으로 객체 키 추출

객체 배열 요소의 키 값을 추출하고 싶을 때 사용 가능하다.

let originalArray = [
  { a: 1, b: 'first' },
  { a: 2, b: 'second' },
  { a: 3, b: 'third' },
];

let newArray = originalArray.map(object => object.b);

console.log(newArray); // output : ['first', 'second', 'third']

각 객체를 가져와 b키에 있는 값을 반환하여 객체 배열을 문자열 배열로 변환한다.

2. 2차원 배열에 map을 사용하는 방법

맵 안에 맵을 중첩하여 사용한다.

let myArray = [[1,2,3,],[4,5,6], [7,8,9]];

let newArray = myArray.map(value => value.map(num => num*2));

console.log(newArray); // output: [[2,4,6],[8,10,12], [14,16,18]];

3. 조건 부 map : 배열의 일부 항목 변경

예를 들어, 배열 안의 숫자 중 10 이상의 숫자만 변경하려고 하는 경우

let originalArray = [5, 10, 15, 20];
 
let newArray = originalArray.map(num => {
  if (num >= 10) {
    return num * 2;
  }
  return num;
});
 
console.log(newArray); // output: [5, 20, 30, 40]

삼항 연산자를 사용하면 훨씬 더 짧게 작성할 수 있다.


let originalArray = [5, 10, 15, 20];

let newArray = originalArray.map(number => number >= 10? number * 2 : number, );

console.log(newArray); // output: [5, 20, 30, 40]

참고
Array.prototype.map() - JavaScript | MDN
Deep Dive into JavaScript's Array Map Method

profile
Convinced myself, I seek not to convince.

0개의 댓글