조씨의 개발 블로그

[JavaScript] reduce 활용하기 본문

JavaScript/ECMAScript

[JavaScript] reduce 활용하기

JoC 2020. 4. 29. 10:52

Array.reduce


reduce 함수는 배열의 요소들을 하나씩 돌면서, 이전 콜백의 리턴 값을 넘겨받아 작업을 수행하는 메서드이다.

arr.reduce(callback( 콜백함수 리턴값, 배열의 요소의값[, 배열 요소의 index[, 배열]] )[, 콜백함수 리턴값의 초기 값])

일단, reduce의 기본 형태 값이다 이제부터 예제를 보면서 알아보도록 하겠다.

 

가장 기본적으로 배열의 합을 구하는 코드이면서 reduce의 가장 기본형이다.

let sum = [1, 2, 3, 4, 5]
var a = sum.reduce(function (tot, el, i) {
  return tot + el
}, 0)
// a = 15
// sum = [1, 2, 3, 4, 5]

// 1번째 tot = 0, el = 1, i = 0, return 1
// 2번째 tot = 1, el = 2, i = 1, return 3
// 3번째 tot = 3, el = 3, i = 2, return 6
// 4번째 tot = 6, el = 4, i = 3, return 5
// 5번째 tot = 10, el = 5, i = 4, return 15

//arrow function
let sum = [1, 2, 3, 4, 5]
var a = sum.reduce(
  ( tot, el ) => tot + el,
  0
)

reduce는 배열의 길이 만큼 돌면서 tot라는 변수에 콜백의 리턴 값을 누적시켜 돌려주는 메서드이다. 이때 배열 sum의 값은 변화가 없고, arrow 함수 사용도 가능하다.

 

또한 reduce는 object 배열에도 활용이 가능하다.

let initialValue = 0

let sum = [{x: 1}, {x: 2}, {x: 3}]
sum.reduce(function (tot, el) {
    return tot + el.x
}, initialValue)

console.log(sum) // 6

와 같이 계산도 할 수 있고, 같은 property를 가진 object 배열을 다음과 같이 그룹핑과 카운팅도 할 수 도 있다.

//그룹핑
let people = [
  { name: 'Alice', age: 21 },
  { name: 'Max', age: 20 },
  { name: 'Jane', age: 20 }
];

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

let groupedPeople = groupBy(people, 'age')
// groupedPeople is:
// { 
//   20: [
//     { name: 'Max', age: 20 }, 
//     { name: 'Jane', age: 20 }
//   ], 
//   21: [{ name: 'Alice', age: 21 }] 
// }
//카운팅
let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']

let countedNames = names.reduce(function (allNames, name) { 
  if (name in allNames) {
    allNames[name]++
  }
  else {
    allNames[name] = 1
  }
  return allNames
}, {})
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

를 활용한다면 https://jo-c.tistory.com/49와 같은 알고리즘 문제도 쉽게 해결 할 수 있다.

 

이 외에도 다양한 활용 방법들이 있다.

// concat을 사용하여 하나의 배열로 만든다.
let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  ( accumulator, currentValue ) => accumulator.concat(currentValue),
  []
)

// [0, 1, 2, 3, 4, 5]

concat을 활용하여 여러개의 배열을 하나의 배열로 만든다거나 

let myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd']
let myOrderedArray = myArray.reduce(function (accumulator, currentValue) {
  if (accumulator.indexOf(currentValue) === -1) {
    accumulator.push(currentValue)
  }
  return accumulator
}, [])

//[ 'a', 'b', 'c', 'e', 'd' ]

indexOf를 사용하여 중복된 원소를 제거할 수 있다.

 

 

출처 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Comments