JavaScript: Array Methods: map(), filter(), reduce()

Sangmin Na·2021년 6월 24일
0

JavaScript

목록 보기
5/7
post-thumbnail

이번 챕터도 알고리즘을 풀다가 필요한 메소드를 발견하여 정보를 찾아보며 공부한 내용으로 포스팅하게 되었습니다. 공부는 왕도도 없고 끝도 없는 것 같네요 ㅎㅎ 여러분들 힘냅시다! 피드백은 언제나 감사히 받겠습니다 😊


Array Methods: map(), filter(), reduce()

"Map, reduce, and filter are all array methods in JavaScript. Each one will iterate over an array and perform a transformation or computation. Each will return a new array based on the result of the function. "

map(), filter(), reduce()는 Array 메소드이다. 각 메소드는 Array를 for문 처럼 한 차례씩 데이터를 변환(Transformation하거나 계산(Computation)을 할 수 있다. 각 메소드는 함수(Function)의 결과에 따라 새로운 Array을 반환한다.


Array.map()

Map()은 기존의 배열로 부터 새로운 배열을 만들어 낸다. 기존의 배열의 각각의 Element에 Function을 적용하여 새로운 배열을 반환한다. 예시를 보면 이해가 금방 된다.

Syntax

var new_array = arr.map(function callback(element, index, array) {
    // Return value for new_array
}[, thisArg])
  • 여기서 Parameter인 Element는 생략할 수 없다.
  • 만약, 생략을 원할 경우function callback(_, index, array) undescore를 사용하여 생략하도록 권장한다.

Example

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(item => item * 2);
console.log(doubled); // [2, 4, 6, 8]
  • 다음은 Array numbers에 속해있는 Elements에 2씩 곱하여 새로운 Array을 만드는 예시이다.
  • const doubled = numbers.map(item => item * 2);의 뜻은 무엇일까?
  • Array numbers안에서 numbers들의 Element을 하나하나씩 가져올거야. 그리고 이를 item이라고 부를게. 그리고 이 item에 2를 곱해서 새로운 Array에 Element로 넣어.

Array.Filter()

Filter를 단어 그대로 이해하면 쉽다. 과학 시간에 실험할 때 사용하는 거름종이라고 생각하면 된다. Filter는 일정한 조건에 충족한 Element들만 가지고 새로운 Array를 생성할 수 있다.

Syntax

var new_array = arr.filter(function callback(element, index, array) {
    // Return true or false
}[, thisArg])

Filter()는 Map()와 아주 비슷하다. 그러나, Filter는 Callback Funtion안에서 true값 혹은 false을 반환해야 한다. 그렇지 않으면, 원하는 대로 메소드가 실행되지 않을 것이다.


Example

const numbers = [1, 2, 3, 4];
const evens = numbers.filter(item => item % 2 === 0);
console.log(evens); // [2, 4]
  • 결과는 [2, 4]을 반환한다.
  • numbers.filter(item => item % 2 ===0); 를 해석해보자.
  • Array numbers안에 있는 Elements을 필터링할 건데 각 Element는 item이라고 부를거고 조건은 item를 2로 나누었을 때 나머지가 0인 수들만 필터링할거야.
  • 2로 나누어져 나머지(remainder)가 0인 경우는 짝수(Even)인 경우이다!

Array.Reduce()

Reduce()는 Array의 Elements을 하나의 Value로 변환하기 위한 메소드이다.

Syntax

// Arrow function
reduce((accumulator, currentValue) => { ... } )
reduce((accumulator, currentValue, index) => { ... } )
reduce((accumulator, currentValue, index, array) => { ... } )
reduce((accumulator, currentValue, index, array) => { ... }, initialValue)
  • 여기서 accumulator, currentvalue이 두가지의 Parameter가 가장 많이 사용된다.
  • 비유를 일상생활에 비교하자면 사람 햄버거게임과 같은 원리다. 내 친구 한명 한명이 쌓여갈 수록 가해지는 무게가 증가하지않는가? reduce도 똑같다.
  • acuumulator는 점점 위로 쌓여져가는 내 친구들의 몸무게고 currentValue는 다음 차례에 내 위에 올라가는 다른 친구와 같다.
  • intialValue는 처음 reduce를 실행하기 전에 초기값이다. 0이면 0부터 시작한다.

Example

const weightFriends = [60, 80, 100, 70];
const sum = weightFriends.reduce(function (acc, cur) {
  return acc + cur;
}, 0);
console.log(310); // 310
  • 초기값은 0이다. 그러므로 0이란 숫자에서 시작을 한다.
  • weightFriends의 첫 Element인 60을 cur에 넣는다. 그 후에 acc + cur을 실행한다. 초기 값은 0이므로 acc는 0 그러므로 실행 값들은 0 + 60 이를 return하면 다음 acc값에 적용한다.
  • 두 번째 Element인 80을 cur에 넣는다. 그 후에 acc + cur을 실행한다. acc는 첫 번째 Element 60이 더 해진60 + 80 이를 return하게 되면 다음 세 번쨰 실행에는 acc가 140이 된다.
  • 이러한 똑같은 방식으로 마지막 Element까지 실행된다.

Reference

0개의 댓글