Honey-Programming

reduce 메소드 본문

JAVASCRIPT

reduce 메소드

Latte_is_horse 2020. 7. 23. 12:23

# reduce (배열을 순회하며 인덱스 데이터를 줄여가며 하나의 결과값을 반환)

원본 배열은 바뀌지 않고 새로운 배열을 만든다. (immutable)

 

문법 : reduce(callback(accumulator, currentValue[, currentIndex [, array]])[, initialValue])

callback: 각 요소에 대해 실행할 함수(테스트를 통과하지 못한 배열 요소(false)는 버리고 새로운 배열에 포함되지 않는다.)

  • accumulator : 누적값
  • currentValue : 현재 배열 내 처리되고 있는 요소
  • currentIndex : 현재 배열 내 처리되고 있는 요소의 인덱스
  • array : reduce()를 호출한 배열

initialValue: callback 첫 번째 인수의 값사용되는 값(default)

 

반환값 : 누적 계산의 결과 값

 

 

- 기본 동작 방식

크롬창 콘솔에 찍어보면 어떻게 돌아가는지 눈으로 보기 쉽게 이해할 수 있다.

let result = [0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array){
    console.log(`currentIndex : ${currentIndex}`);
    console.log(`accumulator : ${accumulator}`);
    console.log(`currentValue : ${currentValue}`);
    console.log(`currentIndex : ${currentIndex}`);
    console.log("                              ");
    return accumulator + currentValue;
}, 10); 

console.log("result:", result);
// 초기값은 10으로 처음에 지정 즉, acc 처음에 10으로 시작
// callback  	acc		value		index		array(참조배열)		(acc + value)최종값
// 1번 호출    10		0		0		[0, 1, 2, 3, 4]			10
// 2번 호출    10		1		1		[0, 1, 2, 3, 4]			11
// 3번 호출    11		2		2		[0, 1, 2, 3, 4]			13
// 4번 호출    13		3		3		[0, 1, 2, 3, 4]			16
// 5번 호출    16		4		4		[0, 1, 2, 3, 4]			20

 

- 객체 배열에서의 값 합산

let initialValue = 0;
let list = [{ x : 1 }, { x : 2 }, { x : 3 }];
let sum = list.reduce(function (accumulator, currentValue) {
// console.log(`accumulator : ${accumulator}`);
// console.log(`currentValue : ${currentValue.x}`);
// console.log("                              ");   
  return accumulator + currentValue.x;
}, initialValue) // 초기값은 맨위에 전역변수(initialValue)로 값을 0으로 주어짐

console.log(sum) // 6
// callback  	acc		value		index		array(참조배열)		(acc + value)최종값
// 1번 호출    0		1		0		list				1
// 2번 호출    1		2		1		list				3
// 3번 호출    3		3		2		list				6

 

- 중첩 배열 펼치기

let arr = [[0, 1], [2, 3], [4, 5]];
let flattened = arr.reduce(function(accumulator, currentValue) {
// console.log(`accumulator : ${accumulator}`);
// console.log(`currentValue : ${currentValue}`);
  return accumulator.concat(currentValue);
    }
,[]); // 초기값은 [](빈 배열)로 정의 
console.log(flattened); // [0, 1, 2, 3, 4, 5] flattened = 합쳐진이라는 뜻
// callback  	acc		value		index		array(참조배열)		(acc + value)최종값
// 1번 호출    []		[0, 1]		0		arr			[0, 1]
// 2번 호출    [0, 1]		[2, 3]		1		arr			[0, 1, 2, 3]
// 3번 호출    [0, 1, 2, 3]	[4, 5]		2		arr			[0, 1, 2, 3, 4, 5]

 

- 속성으로 객체 분류하기

let Info = [
  { name : 'Alice', age : 21 },
  { name : 'Max', age : 20 },
  { name : 'Jane', age : 20 }
];

function groupBy(objectArray, property){
    return objectArray.reduce(function (accumulator, currentObj) {
        let key = currentObj[property];
        
        if (!accumulator[key]) {
            accumulator[key] = [];
        }
        accumulator[key].push(currentObj);
        return accumulator;
    }, {});
};

var groupedInfo = groupBy(Info, 'age');
console.log(groupedInfo);
// { 
//   20 : [{name: "Max", age: 20}, {name: "Jane", age: 20}]
//   21 : [{name: "Alice", age: 21}]
// }

 

- 배열의 중복 항목 제거

sort() 메소드는 다음에 정리해서 올릴것이지만 여기 나온김에 찾아보았다.

간단히 말해서 배열의 값을 정렬할 때 사용. 어떤 값들을 특정 순서에 따라서 정렬할 필요가 있을 경우 사용한다.

Ex) 사용자들의 이름을 순서대로 나열하거나 해야 할 때 사용한다.

let arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4];
let result = arr.sort().reduce(function(acc, value) {
// console.log(`acc : ${acc}`);
// console.log(`value : ${value}`);
// console.log(`                              `);
  const length = acc.length
  if (length === 0 || acc[length - 1] !== value) {
    acc.push(value);
  }
  return acc;
}, []); // 초기값 빈 배열로 정의
console.log(result); // [1,2,3,4,5]

 

'JAVASCRIPT' 카테고리의 다른 글

filter 메소드  (0) 2020.07.23
map 메소드  (0) 2020.07.23
forEach 메소드  (0) 2020.07.22
slice, splice, split 메소드  (0) 2020.07.22
immutable vs mutable  (0) 2020.07.21
Comments