thumbnail
배열 고차 함수
JS
2022.08.11

고차함수(Higher-Order Function)는 함수를 인수로 전달받거나 함수를 반환하는 함수를 말하며 이때 인자를 콜백 함수라 한다.

자주 쓰이는 Array 고차 함수

Array.prototype.filter - 콜백 함수의 반환값이 true인 요소로만 구성된 배열 반환

const array = [1,2,3,4,5];
const arrayFilted = array.filter(x => x % 2 === 0);
console.log(arrayFilted); // [2,4]

Array.prototype.forEach - 자신의 내부에서 반복문을 실행.

const array = [1,2,3,4,5];
array.forEach( x => console.log(x * 2))
// 2
// 4
// 6
// 8
// 10

Array.prototype.map - 반환값을 배열로 반환하는 배열 반복문

const array = [1,2,3,4,5];
const arrayMap = array.map(x => x * 2);
console.log(arrayMap); // [2, 4, 6, 8, 10]

Array.prototype.reduce - 하나의 결과값을 만들어 반환하는 배열 반복문

const array = [1,2,3,4,5];
const initial = 0;
const arrayRedcue = array.reduce((prev, cur) => prev + cur, initial);
console.log(arrayRedcue); // 15

Array.prototype.sort - 배열을 오름차순으로 정렬하여 배열을 반환

const array = [3,1,2,5,4];
const arraySort = array.sort();
console.log(arraySort); // [1, 2, 3, 4, 5]

Array.prototype.reverse - 배열의 순서를 반대로 정렬

const array = [1,2,3,4,5];
const arrayRev = array.reverse();
console.log(arrayRev); // [5,4,3,2,1]

Array.prototype.some - 배열에서 하나라도 조건을 만족하면 true 반환 만족하는 값이 하나도 없으면 false 반환

const array = [1,2,3,4,5];
const someTrue = array.some(x => x % 2 === 0);
console.log(someTrue); // true
const someFalse = array.some(x => x < 0);
console.log(someFalse); // false

Array.prototype.every - 배열에서 모두 조건을 만족하면 true 반환 만족하지 못하는 값이 하나라도 있으면 false

const array = [1,2,3,4,5];
const everyTrue = array.every(x => x > 0);
console.log(everyTrue); // true
const everyFalse = array.every(x => x < 5);
console.log(everyFalse); // false

Array.prototype.find - 배열에서 반환값이 true 인 첫번째 값 존재하지 않으면 undefined 반환

const array = [1,2,3,4,5];
const findEle = array.find(x => x > 2);
console.log(findEle); // 3

Array.prototype.findIndex - 배열에서 반환값이 true 인 첫번째 값 존재하지 않으면 -1 반환

const array = [1,2,3,4,5];
const findIdx = array.findIndex(x => x > 2);
console.log(findIdx); // 2
console.log(array[findIdx]); // 3
Thank You for Visiting My Blog, Have a Good Day 😁
© 2022 Developer Minjae, Powered By Gatsby.