가자미의 개발이야기

[JS] reduce 문 본문

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 문을 통해 배열 내의 중복된 알파벳 갯수를 반환하는 예제이다.

'HTML & CSS & JS > JS' 카테고리의 다른 글

[JS] 개체 생성자와 상속  (0) 2021.03.17
[JS] 프로토타입  (0) 2021.03.17
[JS] 인덱스 관련 함수와 map, filter  (0) 2021.03.17
[JS] 독특한 반복문 (for of, for in, for each)  (0) 2021.03.17
[JS] GET 함수와 SET 함수  (0) 2021.03.17