이전 글에 이어 자바스크립트 배열 메소드를 정리해보자.
주어진 배열에서 조건을 만족하는 첫번째 요소를 찾는 메소드이다. 구조는 아래와 같다.
arr.find(callback[, thisArg])
var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
function findCherries(fruit) {
return fruit.name === 'cherries';
}
console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }
const inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
const result = inventory.find(fruit => fruit.name === 'cherries');
console.log(result) // { name: 'cherries', quantity: 5 }
주어진 함수의 조건을 만족하는 모든 요소를 모아 새로운 배열로 반환한다. 구조는 아래와 같다.(콜백 함수의 리턴값이 true인 요소를 모은다.)
arr.filter(callback(element[, index[, array]])[, thisArg])
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다. 구조는 다음과 같다.
arr.map(callback(currentValue[, index[, array]])[, thisArg])
const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]
filter와 map이 아주 유사해 보인다.
일단 filter에는 조건을 넣고, map에는 실행 동작을 넣는 것으로 하자.