Web/javascript

Array - map과 reduce

rockettttman 2021. 2. 2. 16:04

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

 

map은 해당 Array를 반복적으로 돌면서 각 요소들에 대해 callbackFunc를 정할 수 있다. 새로운 객체가 생성되어 리턴되고 기존 배열의 크기를 그대로 반환하기 때문에 아래 코드와 같이 조건에 맞지 않을 경우 해당 인덱스의 값은 undefined를 리턴하게 된다.

var mapTest = [1,2,3,4,5]

var tmp = mapTest.map(v => {	
    if(v>3){
        return v
    }
})

//크기를 그대로 반환
//[undefined, undefined, undefined, 4, 5]

 

2. reduce => 배열.reduce((누적값, 현잿값, 인덱스, 요소) => { return 결과 }, 초깃값);

 

reduce는 배열을 돌면서 이전값들을 가지며 누적 값을 통해 활용할 수 있다. 파라미터로 이전 값과 현재 값 등을 가진다. 때문에 reduce를 사용하여 console을 찍을 경우 인덱스는 1부터 시작하게 된다.

 

reduce를 이용하여 MAX값 구하기

var max = 0;

result.reduce((bef, cur) => {
    console.log(max, cur)
    max = Math.max(max, cur)
});


//max = 5

//console
//0 2
//2 3
//3 4
//4 5

reduce를 이용하여 배열 값 더하기

var sumArr = [1,2,3,4,5];

var result = sumArr.reduce((bef, cur) => {
    return bef + cur;
})

//result = 15

reduce를 이용하여 오브젝트 객체 별 누적 값

const fruit = ['apple', 'grape', 'banana', 'apple', 'orange', 'grape', 'apple', 'orange'];
 
const result = fruit.reduce((object, currentValue) => {
    if (!object[currentValue]) {
        object[currentValue] = 0;
    }
    object[currentValue]++;
 
    return object;
}, {});
 
//{apple: 3, grape: 2, banana: 1, orange: 2}

 

참고 : 2dubbing.tistory.com/55

www.zerocho.com/category/JavaScript/post/5acafb05f24445001b8d796d