TIL wecode 07. map, filter and reduce

이조은·2020년 7월 26일
0

TIL wecode

목록 보기
7/36

map

  • The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

  • map()은 주어진 어레이의 각 요소에 함수를 적용한 결과로 이루어진 새로운 배열을 형성한다.

  • map을 사용하는 방법
    map은 콜백 함수를 아규먼트로 받는다. 콜백 함수의 아규먼트는 currentValue(필수, 처리되고 있는 현재의 엘레먼트), index(현재의 엘레먼트의 인덱스), original array로 볼 수 있다.

const myArray = [1, 2, 3, 4];

const myArrayTimesTwo = myArray.map((value, index, array)=>{
  return value * 2;
});

console.log(myArray); //[1, 2, 3, 4]
console.log(myArrayTimesTwo); //[2, 4, 6, 8]
  • map을 사용하면 안 될 때
    : 반환된 어레이를 사용하지 않는다면 map을 쓸 이유가 없다. 대신 forEach나 for...of를 사용하도록 하자.

filter

  • The filter() method creates a new array with all elements that pass the test implemented by the provided function.

  • filter()는 어레이에서 주어진 조건에 부합하는 모든 요소들로 이루어진 새로운 배열을 형성한다.

  • filter을 사용하는 방법
    map과 아주 비슷하다.

const myArray = [1, 2, 3, 4];

const myEvenArray = myArray.filter((value, index, array)=>{
  return value % 2 === 0;
});

console.log(myArray); //[1, 2, 3, 4]
console.log(myEvenArray); //[2, 4]
var strings = ["hello", "Matt", "Mastodon", "Cat", "Dog"];

var fitered = strings.filter(str => {
  return str.includes("at");
});

console.log(filtered); //["Matt", "Cat"]

reduce

  • The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.

  • reduce()는 어레이의 각 요소에 대해 reducer 함수를 실행하게 되고 이는 단일한 결과 값을 도출한다.

  • reduce을 사용하는 방법
    map, filter와 유사하지만 콜백의 아규먼트에서 다르다. reduce의 콜백은 accumulator(필수, accumulator는 모든 return value를 서서히 축적함), current value(필수), current index, whole array를 받는다. 그리고 마지막에 initial value를 선택적으로 받게 되는데, 이때 시작 값이 생략된다면 배열의 첫 번째 요소가 첫 accumulator 값이 된다.

const myArray = [1, 2, 3 , 4];

const sum = myArray.reduce((acc, currValue, currIndex, array) => {
  return acc + currValue;
}, 0);

const avg = sum / myArray.length;

console.log(avg); //2.5
profile
싱글벙글

0개의 댓글