본문 바로가기
개발 관련 지식/JS

map 함수

by 권태일1147 2020. 3. 8.
배열의 모든 요소를 함수에 적용하여 나온 결과를 모아 새로운 배열을 생성해내는 함수

filter 함수와의 차이점은.

filter 함수는 요소를 콜백함수에 적용해 결과가 true인 것들을 반환해 새로운 배열로 만들어내는 함수이다.

틈틈이 꾸준하게 - filter 함수

 

filter 함수

배열이나 JSON 객체에 대해 콜백함수의 조건에 해당하는 모든 요소가 있는 배열을 새로 생성하는 기능. arr.filter(callbackFunction(element [, index [, array] ] ) [, thisArg] ) filter함수는 콜백함수와, thi..

im-recording-of-sw-studies.tistory.com

 

기본적으로 배열의 요소만큼 반복한다고 생각하면 된다.

arr.map(callback(currentValue, index, array), thisArg)

매개변수로 callbackFunction과 thisArg가 있다.

callbackFunction의 매개변수로는 currentValue, index, array가 있는데

currentValue는 현재 돌고 있는 요소의 값

index는 현재 돌고 있는 요소의 인덱스

array는 map에 적용되는 배열

그리고 thisArg는 callbackFunction에서 this로 사용되는 매개변수이다.

index, array, thisArg는 선택적으로 사용할 수 있다.

 

 

예제를 해보자.

const arr = [1, 2, 3]
const newArr = arr.map(function(value, index, array){
    console.log("현재 돌고 있는 요소의 value : ", value)
    console.log("현재 돌고 있는 요소의 index : ", index)
    console.log("map에 사용되고 있는 배열 : ", array)
})

결과

 

 

제곱근 숫자 배열 만들기

const arr = [4, 49, 100]
const newArr = arr.map(Math.sqrt)
console.log(newArr)

// [2, 7, 10]

 

 

thisArg를 이용해 숫자를 두배로 만들기

const arr = [4, 49, 100]
const Arg = 2
function double(value){
    const doubleNum = value * this
    return doubleNum
}
const newArr = arr.map(double, Arg)
console.log(newArr)

// [8, 98, 200]

 

 

json array에서 value만 뽑아오기

const arr = [
    {key: 1, food: '치킨'}, 
    {key: 2, food: '아구찜'},
    {key: 3, food: '우렁된장국'}
]
function onlyFood(value){
    const foodVal = value.food
    return foodVal
}
const newArr = arr.map(onlyFood)
console.log(newArr)

// ["치킨", "아구찜", "우렁된장국"]

 

 

map도 filter처럼 내부에 조건을 줘서 특정 요소만 가져올 수도 있지만,

map은 내용이 바뀐 새로운 배열을 가져올 때 사용하고,

조건을 충족하는 요소를 가져올 때는 filter를 사용하자.

'개발 관련 지식 > JS' 카테고리의 다른 글

Virtual scroll ( 분석하기 위해 남김 )  (0) 2020.03.28
callback function - JS  (0) 2020.03.09
eslint  (0) 2020.03.07
babel  (0) 2020.03.06
split : 문자열 분할 함수  (0) 2020.03.05