map

이은지·2022년 11월 5일
0

개념

목록 보기
1/8

map이란?

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

array.map(callbackFunction(currentValue, index, array), thisArg)

  • callbackFunction : 콜백함수
  • currentValue : 배열 내 현재 값
  • index : 배열 내 현재 값의 인덱스
  • array : 현재 배열
  • thisArg : callbackFunction 내에서 this로 사용될 값

특징

  1. map은 호출한 배열의 값을 변형하지 않는다
  2. 호출할 배열에 빈값이 있으면 결과도 빈값으로 반환한다
  3. 콜백할 함수를 정하지 않았을때는 익명함수형태로 쓰인다
    function(x) {return x + 2}

map에서 받는 인자(value, index, array) 이해하기

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

const map1 = array1.map(function(value, index, array) {
  mapvalue = value;
  mapindex = index;
  maparray = array;
  console.log('value:' + mapvalue, 'index:' + mapindex, 'array' + maparray)
});

console.log(map1);
// value:1 index:0 array1,4,9,16
// value:4 index:1 array1,4,9,16
// value:9 index:2 array1,4,9,16
// value:16 index:3 array1,4,9,16

mdn에서 이해안갔던 예제 (객체 재구성)

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

const mapArray = array.map(function(item){
   const newObject = {}; //{key : value}
  
   //item.value를 newObject라는 객체의 item.key로 넣겠다
   newObject[item.key] = item.value;
   return newObject;
});
console.log(mapArray); //[{1:10}. {2:20}, {3, 30}]

제곱근을 구해보자

  • Math.sqrt() : 숫자의 제곱근을 반환하는 함수
const numbers = [4,9,16,25,36];
const result = numbers.map((number) => Math.sqrt(number))
console.log(result);

결과

[2,3,4,5,6]

주어진 배열 A의 모든 요소에 곱하기 2를 한 배열

const A = [1,2,3,4,5,6,7,8,9,10];
const E = A.map((number) => number * 2)
console.log(E);

결과

[2,4,6,8,10,12,14,16,18,20]

주어진 배열 C의 모든 요소마다, 요소의 index를 곱한 것

const C = [6,7,8,9,10];
const F = C.map((number, index) => number * index)
console.log(F);

결과

[0,7,16,27,40]

주어진 배열 A의 요소 중 짝수인 것에는 곱하기 2를, 홀수인 것에는 더하기 2를 한 것

const A = [1,2,3,4,5,6,7,8,9,10];
const G = A.map((number) =>{
  if (number % 2 === 0) {
  	number * 2
  } else {
  	number + 2
  }
})
console.log(G);
  • if문을 삼항연산자로 바꾼다면?
const A = [1,2,3,4,5,6,7,8,9,10];
const G = A.map((number) => {
  return number % 2 === 0 ? number * 2 : number + 2
})
console.log(G);

array안에 array가 있을 때 요소에 * 2를 해주는 배열을 반환

const numbers = [[1,2,3],[4,5,6],[7,8,9]];
const newNumbers = numbers.map(array => array.map(number => number *2));
console.log(newNumbers);
  • 좀더 풀어서 쓰면 어떨까
const numbers = [[1,2,3],[4,5,6],[7,8,9]];
function multiply(number) {
	return number * 2
}
//map(함수) 이렇게 실행시킬수도 있다
const newNumbers = numbers.map(array => array.map(multiply));
console.log(newNumbers);

0개의 댓글