Map, Filter, Reduce

김형진·2024년 8월 12일
post-thumbnail

Map

배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환함

let arr = [1, 2, 3, 4, 5];

const map1 = arr.map((x) => x * 2);

console.log("map1", map1);
map1 [ 2, 4, 6, 8, 10 ]
arr.map(callback(currentValue[,index[,arr]])[,thisArg])
let arr = [1, 2, 3, 4, 5];

const map1 = arr.map(
  function (item, index, array) {
    console.log(item, index, array, this);
    return item * 2;
  },
  { a: "a" }
);

console.log("map1", map1);

//result
1 0 [ 1, 2, 3, 4, 5 ] { a: 'a' }
2 1 [ 1, 2, 3, 4, 5 ] { a: 'a' }
3 2 [ 1, 2, 3, 4, 5 ] { a: 'a' }
4 3 [ 1, 2, 3, 4, 5 ] { a: 'a' }
5 4 [ 1, 2, 3, 4, 5 ] { a: 'a' }
map1 [ 2, 4, 6, 8, 10 ]

Filter

주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환

const words = [
  "spray",
  "limit",
  "elite",
  "exuberant",
  "destruction",
  "present",
];

const result = words.filter((word) => word.length > 6);

console.log("result", result);
//result [ 'exuberant', 'destruction', 'present' ]
arr.filter(callback(element[,index[,arr]]),[thisArg])
const words = [
  "spray",
  "limit",
  "elite",
  "exuberant",
  "destruction",
  "present",
];

const result = words.filter(
  function (word, index, array) {
    console.log(word, index, array, this);
    return word.length > 6;
  },
  { a: "a" }
);

console.log("result", result);

//result
spray 0 [ 'spray', 'limit', 'elite', 'exuberant', 'destruction', 'present' ] { a: 'a' }
limit 1 [ 'spray', 'limit', 'elite', 'exuberant', 'destruction', 'present' ] { a: 'a' }
elite 2 [ 'spray', 'limit', 'elite', 'exuberant', 'destruction', 'present' ] { a: 'a' }
exuberant 3 [ 'spray', 'limit', 'elite', 'exuberant', 'destruction','present' ] { a: 'a' }
destruction 4 [ 'spray', 'limit', 'elite', 'exuberant', 'destruction', 'present' ] { a: 'a' }
present 5 [ 'spray', 'limit', 'elite', 'exuberant', 'destruction', 'present' ] { a: 'a' }
result [ 'exuberant', 'destruction', 'present' ]

Reduce

배열의 각 요소에 대해 주어진 리듀서 함수를 실행하고, 하나의 결괏값을 반환

arr.reduce(reducer 함수, initialValue)

reducer 함수는 4개의 인자를 가짐

  • 누산기: acc
  • 현재 값: cur
  • 현재 인덱스: idx
  • 원본 배열: src
let arr = [1, 2, 3, 4, 5];

const reduce = arr.reduce(function (acc, curVal, curIdx, arr) {
  return acc + curVal;
});

console.log("reduce", reduce);
//reduce 15
const reduce1 = arr.reduce(function (acc, curVal, curIdx, arr) {
  return acc + curVal;
}, 10); //두번째 인자로 초기값 제공

console.log("reduce", reduce1);
//reduce 25

0개의 댓글