TIL/Javascript

TIL.89 Javascript_map 함수

codermun 2021. 1. 5. 13:52
728x90
반응형

map() method는 호출 배열의 모든 요소에 대해 제공된 함수를 호출 한 결과로 채워진 새 배열을 만듭니다 .

 배열.map((요소, 인덱스, 배열) => { return 요소 });

 

map함수는 callbackFunction을 실행한 결과를 가지고 새로운 배열을 만들 때 사용한다.

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

callbackFunction, thisArg 두개의 매개변수가 있고
callbackFunction은 currentValue, index, array 3개의 매개변수를 갖는다.

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

여러가지 예시

제곱근 구해보기

var numbers = [4, 9, 16, 25, 36];
var result = numbers.map(Math.sqrt);
console.log(result);

배열 값 *2

// array*2 아래 3개는 모두 결과값이 동일하다.

var number_2 = [1,2,3,4,5,6,7,8,9];
var newnumber_2 = number_2.map(number => number *2);
console.log(newnumber_2)
var number_3 = [1,2,3,4,5,6,7,8,9];
var newnumber_3 = number_3.map(function (number){return number*2;});
console.log(newnumber_3)
var number_4 = [1,2,3,4,5,6,7,8,9];
function TTEST(number){return number*2;};

var newnumber_4 = number_4.map(TTEST);
console.log(newnumber_4)

 


 map 함수는 filter함수와 같이 Object(객체)타입도 컨트롤 할 수도 있다.

var students = [
    {id:1, name:"james"},
    {id:2, name:"tim"},
    {id:3, name:"john"},
    {id:4, name:"brian"}
  ];

map 함수를 이용해 이름만 출력하기.

var students = [
    {id:1, name:"james"},
    {id:2, name:"tim"},
    {id:3, name:"john"},
    {id:4, name:"brian"}
  ];

  var names = students.map(student => student.name);
  console.log(names);
  
// [ 'james', 'tim', 'john', 'brian' ]

map 함수를 이용해 id만 출력하기.

var students = [
    {id:1, name:"james"},
    {id:2, name:"tim"},
    {id:3, name:"john"},
    {id:4, name:"brian"}
  ];

  var names = students.map(student => student.id);
  console.log(names);
  // [ 1, 2, 3, 4 ]

배열 안에 배열이 있는 경우

map 안에 map을 중첩사용하여 아래와 같이 사용할 수 있다.

var numbers = [[1,2,3],[4,5,6],[7,8,9]]; //array안에 array가 있는 경우
var newNumbers = numbers.map(array => array.map(number => number *2));
console.log(newNumbers);
// [ [ 2, 4, 6 ], [ 8, 10, 12 ], [ 14, 16, 18 ] ]

map 함수는 기존의 배열을 callbackFunction에 의해 새 배열을 만드는 함수이다.
그러니 기존의 배열이 변하지는 않는다.

 

 

출처 : velog.io/@daybreak/Javascript-map%ED%95%A8%EC%88%98

 

[Javascript] map함수

map함수는 callbackFunction을 실행한 결과를 가지고 새로운 배열을 만들 때 사용한다. array.map(callbackFunction(currenValue, index, array), thisArg)filter, forEach와 같은 구문이다.

velog.io

 

728x90
반응형