HTML & CSS & JS/JS

[JS] reduce 문

가자미 2021. 3. 17. 16:39

reduce : 콜백을 모든 원소들이 반복하고 그 값을 누적한다.

const numbers = [1,2,3,4,5];

const sum = numbers.reduce((accumulator, current)=>accumulator+current, 0)
//accumulator 결과값이 누적, current 현재 배열원소

//reduce 활용
const alpahnbet=[a,a,a,b,c,c,d,e];
alphabets.reduce((acc,current)=>{
    if(acc[current]){
        acc[current]+=1;
    }else{
        acc[current]=1;
    }
    return acc;
});

reduce 문을 통해 배열 내의 중복된 알파벳 갯수를 반환하는 예제이다.