자바스크립트에는 기본적으로 내장(built-in)되어 있는 고차 함수들이 있다.
: 배열 메소드들 중 일부가 고차 함수에 해당
map : 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환
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]
구문
arr.map(callback(currentValue[, index[, array]])[, thisArg])
const cartoons = [
{
id: 1,
bookType: 'cartoon',
title: '식객',
subtitle: '어머니의 쌀',
createdAt: '2003-09-09',
genre: '요리',
artist: '허영만',
averageScore: 9.66,
},
{
id: 2,
// .. 이하 생략
},
// ... 이하 생략
]; // 만화책의 모음
const findSubtitle = function (cartoon) {
return cartoon.subtitle;
}; // 만화책 한 권의 제목을 리턴하는 로직(함수)
const subtitles = cartoons.map(findSubtitle); // 부제의 모음
filter : 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환
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"]
구문
arr.filter(callback(element[, index[, array]])[, thisArg])
const cartoons = [
{
id: 1,
bookType: 'cartoon',
title: '식객',
subtitle: '어머니의 쌀',
createdAt: '2003-09-09',
genre: '요리',
artist: '허영만',
averageScore: 9.66,
},
{
id: 2,
// .. 이하 생략
},
// ... 이하 생략
]; // 단행본의 모음
const isCreatedAt2003 = function (cartoon) {
const fullYear = new Date(cartoon.createdAt).getFullYear()
return fullYear === 2003;
}; // 단행본 한 권의 출판판년도가 2003인지 확인하는 함수
const filteredCartoons = cartoons.filter(isCreatedAt2003); // 출판년도가 2003년인 책의 모음
reduce : 배열의 각 요소에 대해 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과값을 반환
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
구문
arr.reduce(callback[, initialValue])
const cartoons = [
{
id: 1,
bookType: 'cartoon',
title: '식객',
subtitle: '어머니의 쌀',
createdAt: '2003-09-09',
genre: '요리',
artist: '허영만',
averageScore: 9.66,
},
{
id: 2,
// .. 이하 생략
},
// ... 이하 생략
]; // 단행본의 모음
const scoreReducer = function (sum, cartoon) {
return sum + cartoon.averageScore;
}; // 단행본 한 권의 평점을 누적값에 더한다.
let initialValue = 0 // 숫자의 형태로 평점을 누적한다.
const cartoonsAvgScore = cartoons.reduce(scoreReducer, initialValue) / cartoons.length;
// 모든 책의 평점을 누적한 평균을 구한다.
function joinName(resultStr, user) {
resultStr = resultStr + user.name + ', ';
return resultStr;
}
let users = [
{ name: 'Tim', age: 40 },
{ name: 'Satya', age: 30 },
{ name: 'Sundar', age: 50 }
];
users.reduce(joinName, '');
function makeAddressBook(addressBook, user) {
let firstLetter = user.name[0];
if(firstLetter in addressBook) {
addressBook[firstLetter].push(user);
} else {
addressBook[firstLetter] = [];
addressBook[firstLetter].push(user);
}
return addressBook;
}
let users = [
{ name: 'Tim', age: 40 },
{ name: 'Satya', age: 30 },
{ name: 'Sundar', age: 50 }
];
users.reduce(makeAddressBook, {});
{
T: [
{ name: 'Tim', age: 40 }
],
S: [
{ name: 'Satya', age: 30 },
{ name: 'Sundar', age: 50 }
]
}