고차함수는
함수를 인수로전달받거나 함수를 반환하는 함수입니다.
고차함수는 불변성을 지향하는
함수형 프로그래밍에 기반을 두고 있습니다.
함수형 프로그래밍은 순수 함수를 통해 부수 효과를 최대한 억제하여
오류를 피하고, 프로그램의 안정성을 높이려는 의도가 있습니다.
자바스크립트에는 다양한 고차함수가 있고,
특히 배열 고차함수는 활용도가 높습니다.
sort() 메서드는 배열의 요소를 오름차순 정렬합니다.
원본 배열을 직접 변경합니다.
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// Expected output: Array ["Dec", "Feb", "Jan", "March"]
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// Expected output: Array [1, 100000, 21, 30, 4]
reverse() 메서드는 배열의 순서를 반전합니다.
원본 배열을 직접 변경합니다.
배열의 요소를 내림차순 정렬하고 싶다면,
sort() 메서드를 먼저 사용하고 reverse 메서드를 사용하면 됩니다.
const a = [1, 2, 3];
console.log(a); // [1, 2, 3]
a.reverse();
console.log(a); // [3, 2, 1]
forEach() 메서드는
주어진 함수를 배열 요소 각각에 대해 실행합니다.
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
// Expected output: "a"
// Expected output: "b"
// Expected output: "c"
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]
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"]
reduce() 메서드는
배열의 각 요소에 대해 주어진 리듀서 (reducer) 함수를 실행하고,
하나의 결과값을 반환합니다.
리듀서 함수는 네 개의 인자를 가집니다.
누산기 (acc)
현재 값 (cur)
현재 인덱스 (idx)
원본 배열 (src)
리듀서 함수의 반환 값은 누산기에 할당되고, 누산기는 순회 중 유지되므로 결국 최종 결과는 하나의 값이 됩니다.
const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => accumulator + currentValue,
initialValue
);
console.log(sumWithInitial);
// Expected output: 10
some() 메서드는 배열 안의 어떤 요소라도
주어진 함수를 적어도 하나라도 통과하는지 테스트합니다.
const array = [1, 2, 3, 4, 5];
// Checks whether an element is even
const even = (element) => element % 2 === 0;
console.log(array.some(even));
// Expected output: true
every() 메서드는 배열 안의 모든 요소가 주어진 함수를 통과하는지 테스트합니다.
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
// Expected output: true
find() 메서드는 주어진 함수를 만족하는 첫 번째 요소의 값을 반환합니다.
그런 요소가 없다면 undefined를 반환합니다.
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
// Expected output: 12
findIndex() 메서드는 주어진 함수를 만족하는 배열의 첫 번째 요소에 대한
인덱스를 반환합니다.
만족하는 요소가 없으면 -1을 반환합니다.
const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber));
// Expected output: 3