자바스크립트 map, filter, reduce

KyungminLee·2021년 5월 7일

Javascript

목록 보기
1/2
post-thumbnail

map, filter, reduce 동작 원리

자바스크립트에서 map(), filter(), reduce() 메소드는 배열 요소를 나열하거나, 특정 조건에 맞게 보여줄 때 자주 쓰인다.

예제 배열

const listData = [
  {
    id: 1,
    text: 'test1',
  },
  {
    id: 2,
    text: 'test2',
  },
  {
    id: 3,
    text: 'test3',
  },
  {
    id: 4,
    text: 'test4',
  },
  {
    id: 5,
    text: 'test5',
  },
]

👉 map()

// Array.prototype.map()
arr.map(callback(currentValue[, index[, array]])[, thisArg])
const realMapResult = listData.map(list => list.text)
console.log(realMapResult)
// output: ["test1", "test2", "test3", "test4", "test5"]

실제 map()과 같은 결과를 얻기 위해선??

const mockMap = list => {
  let result = [] // map()은 새로운 배열을 반환
  for (const i of list) {
    result.push(i.text)
  }
  return result
}

const result = mockMap(listData)
console.log(result)

👉 filter()

// Array.prototype.filter()
arr.filter(callback(element[, index[, array]])[, thisArg])
const realFilterResult = listData.filter(list => list.text !== 'test1')
console.log(realFilterResult)
// output: [
//   {
//     id: 1,
//     text: 'test2',
//   },
//   {
//     id: 3,
//     text: 'test3',
//   },
//   {
//     id: 4,
//     text: 'test4',
//   },
//   {
//     id: 5,
//     text: 'test5',
//   },
// ]

실제 filter()과 같은 결과를 얻기 위해선??

const mockFilter = list => {
  let result = [] // filter() 역시 새로운 배열을 반환
  for (const i of list) {
    if (i.text !== 'test1') {
      result.push(i) // 해당 조건에 맞는 객체를 push
    }
  }
  return result
}

const result = mockFilter(listData)
console.log(result)

👉 reducer()

reducer() 함수는 네 개의 인자를 받는다.

  1. 누산기accumulator (acc): initialValue가 있을 경우 initialValue이며, 없을 경우 콜백의 반환값을 누적
  2. 현재 값 (cur)
  3. 현재 인덱스 (idx): initialValue가 있을 경우 0, 아니면 1부터 시작
  4. 원본 배열 (src)
const array1 = [1, 2, 3, 4]
const resultOfReducer = array1.reduce(
  (accumulator, currentValue, currentIndex, array) => {
    console.log('accumulator', accumulator) // output: 10 11 13 16
    console.log('currentValue', currentValue) // output: 1 2 3 4
    console.log('currentIndex', currentIndex) // output: 0 1 2 3
    console.log('array', array) // output: [1, 2, 3, 4]
    return accumulator + currentValue
  },
  10//initValue
)
console.log(resultOfReducer) // output: 20(10 + 1 + 2 + 3 + 4)
//initValue가 없으면 (1 + 2 + 3 + 4)
//string
const resultOfReducer = listData.reduce(
  (accumulator, currentValue, currentIndex, array) => {
    return accumulator + currentValue.text + ' '
  },
  ''
)
console.log(resultOfReducer)// "test1 test2 test3 test4 test5"
profile
끊임없이 발전해가는 개발자.

0개의 댓글