Javascript에서 유용하게 사용할 수 있는 배열 함수들이다.
알고리즘 + 코드 리팩토링을 위해 메서드는 잘 활용하면 정말정말 좋다
그 중에서 가장 많이 쓰이고 비슷한 세 가지를 비교해보려 한다.
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])
filter()는 배열 내 각 요소에 대해 한 번 제공된 callback 함수를 호출해, callback이 true로 강제하는 값을 반환하는 모든 값이 있는 새로운 배열을 생성한다.
map
은 배열의 길이만큼 값이 나오지만,
filter
는 조건에 따라 배열의 길이보다 적거나 같게 나온다.
또한 filter
는 배열의 원소를 변형하여 반환할 수 없다.
: 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환
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 classmate = [" "," "," "]
classmate.map((item)=>(item+" "))
=> (3)[" "," "," "] .
기본형식은 ((el) => ()) 임
const classmate = [
{name: "진구"},
{name: "비실이"},
{name: "퉁퉁이"}]
//item.name => "진구","비실이","퉁퉁이"
//school
classmate.map((item)=>({name : item.name + "어린이",
school : "떡잎유치원"}))
=> (3)[
{name : "진구어린이",school : "떡잎유치원"},
{name : "비실이어린이",school : "떡잎유치원"},
{name : "퉁퉁이어린이",school : "떡잎유치원"}
]
배열은 map(( ) => ( ))
배열안의 객체는 map(( ) => ({ }))
객체가 들어간 배열은 중괄호{ }로 감싸주어야 한다.
화살표 함수에서 소괄호 생략이 가능하다.
다만 한줄짜리 코드여야한다.
소괄호 생략이 불가능한 경우
리턴값이 객체인 경우
:배열 안의 모든 요소가 주어진 판별 함수를 통과하는지 테스트한다. Boolean 값을 반환
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
// expected output: true
// 화살표 함수
every((element) => { ... } )
every((element, index) => { ... } )
every((element, index, array) => { ... } )// 콜백 함수
every(callbackFn)
every(callbackFn, thisArg)// 인라인 콜백 함수
every(function callbackFn(element) { ... })
every(function callbackFn(element, index) { ... })
every(function callbackFn(element, index, array){ ... })
every(function callbackFn(element, index, array) { ... }, thisArg)
Mdn 참고 https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/every