Array.prototype.filter(), Array.prototype.map(), Array.prototype.reduce()

heyj·2022년 4월 6일
0

HTML/CSS/Javascript

목록 보기
8/8
post-thumbnail

오늘 기술면접을 보며 손코딩을 처음해봤습니다.
(결과는 처참...ㅠㅠ)

그 동안 코드를 짜면서
1) 데이터 흐름을 생각하며 짰는지,
2) 메소드의 내부 동작 원리를 정확히 이해하며 썼는지,
3) 얼마나 생각을 하며 코드를 짰는지..
면접 보는 내내 반성의 시간을 가졌습니다.ㅠㅠ

가장 많이 사용하고 있는 filter, map 메소드를
for, if문으로 직접 구현하는 것을 코드로 짜본적이 있었는데도.. 시간 안에 손으로 쓰지 못했습니다...ㅠㅠ

또 잊을까봐 정리를 하기로 했습니다.

filter는 원하는 요소만 배열에 넣어서 새로운 배열을 만듭니다.
인자로 받은 callback함수가 참을 리턴할 때만 요소로 넣어 배열을 만드는 방식입니다.

filter는 인자로 callbackFn, element, index, array, (thisArg)를 받습니다.

filter(function(element) { /* ... */ })
filter(function(element, index) { /* ... */ })
filter(function(element, index, array){ /* ... */ })
filter(function(element, index, array) { /* ... */ }, thisArg)
function filter(cb, arr) {
  let list = [];
  for (let i = 0; i < arr.length; i++) {
    if(cb(arr[i], i)) list.push(arr[i]);
  }
  return list;
}

map은 요소들을 이용해 새로운 배열을 만듭니다. 이 때 filter와 다른 점은 filter의 경우 callback함수가 참을 리턴하는 요소만을 배열에 넣지만, map은 원래 배열의 길이와 동일한 배열을 만들어 냅니다.

map이 생성하는 배열은 무조건 원본변수와 길이 같으므로, map을 이용할 때에는 새로 배열을 만들어 push를 이용하는 것이 좋습니다.

map(function(element) { /* ... */ })
map(function(element, index) { /* ... */ })
map(function(element, index, array){ /* ... */ })
map(function(element, index, array) { /* ... */ }, thisArg)
function map(cb, arr) {
  let list = [];
  for (let i = 0; i < arr.length; i++) {
    list.push(cb(arr[i], i));
  }
  return list;
}

다음과 같은 코드에서는 undefined인 요소들이 생기는데 새로운 배열에 push를 하지 않을 경우, undefinded이 요소로 들어가게 됩니다.

let a = [10, 11, 12, 13, 14, 15];

let newArr = a.map(
  (v, i) => {
    if (v % 2 === 0) {
      return v;
    }
  },
  [1, 2]
);

console.log(newArr); // [ 10, undefined, 12, undefined, 14, undefined ]

reduce는 filter, map과 달리 값을 생성해서 리턴합니다.

reduce는 첫번째 인자는 콜백함수를 받고, 두 번째 인자는 초기값을 받습니다.

아래 예제의 경우 초기값은 10이고, 콜백함수는 인자로 이전의 반환값(accumulater), 현재값, 현재index, reduce를 호출한 배열(array)을 갖습니다. index, array는 optional입니다.

[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
  return accumulator + currentValue;
}, 10);
function reduece(cb, value) {
  let result = value;
  for (let i = 0; i < a.length; i++) {
    result = cb(result, a[i])
  }
  return result;
}

예제

let a = [10, 11, 12, 13, 14, 15];

let result = a.reduce((acc, a) => {
  return acc - a;
}, 0);
console.log(result); // -75

0개의 댓글