이번 챕터도 알고리즘을 풀다가 필요한 메소드를 발견하여 정보를 찾아보며 공부한 내용으로 포스팅하게 되었습니다. 공부는 왕도도 없고 끝도 없는 것 같네요 ㅎㅎ 여러분들 힘냅시다! 피드백은 언제나 감사히 받겠습니다 😊
"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을 반환한다.
Map()은 기존의 배열로 부터 새로운 배열을 만들어 낸다. 기존의 배열의 각각의 Element에 Function을 적용하여 새로운 배열을 반환한다. 예시를 보면 이해가 금방 된다.
var new_array = arr.map(function callback(element, index, array) {
// Return value for new_array
}[, thisArg])
function callback(_, index, array)
undescore를 사용하여 생략하도록 권장한다.const numbers = [1, 2, 3, 4];
const doubled = numbers.map(item => item * 2);
console.log(doubled); // [2, 4, 6, 8]
const doubled = numbers.map(item => item * 2);
의 뜻은 무엇일까?item
이라고 부를게. 그리고 이 item
에 2를 곱해서 새로운 Array에 Element로 넣어.Filter를 단어 그대로 이해하면 쉽다. 과학 시간에 실험할 때 사용하는 거름종이라고 생각하면 된다. Filter는 일정한 조건에 충족한 Element들만 가지고 새로운 Array를 생성할 수 있다.
var new_array = arr.filter(function callback(element, index, array) {
// Return true or false
}[, thisArg])
Filter()는 Map()와 아주 비슷하다. 그러나, Filter는 Callback Funtion안에서 true
값 혹은 false
을 반환해야 한다. 그렇지 않으면, 원하는 대로 메소드가 실행되지 않을 것이다.
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);
를 해석해보자.item
이라고 부를거고 조건은 item
를 2로 나누었을 때 나머지가 0인 수들만 필터링할거야.Reduce()는 Array의 Elements을 하나의 Value로 변환하기 위한 메소드이다.
// Arrow function
reduce((accumulator, currentValue) => { ... } )
reduce((accumulator, currentValue, index) => { ... } )
reduce((accumulator, currentValue, index, array) => { ... } )
reduce((accumulator, currentValue, index, array) => { ... }, initialValue)
const weightFriends = [60, 80, 100, 70];
const sum = weightFriends.reduce(function (acc, cur) {
return acc + cur;
}, 0);
console.log(310); // 310
weightFriends
의 첫 Element인 60을 cur에 넣는다. 그 후에 acc + cur
을 실행한다. 초기 값은 0이므로 acc는 0 그러므로 실행 값들은 0 + 60
이를 return
하면 다음 acc값에 적용한다.acc + cur
을 실행한다. acc는 첫 번째 Element 60이 더 해진60 + 80
이를 return
하게 되면 다음 세 번쨰 실행에는 acc가 140이 된다.