filter() 란
map() 메서드는 배열 안의 모든 요소들을 각각 순회하며
주어진 함수의 테스트를 통과하는 모든 요소들을 모아서
새로운 배열을 반환한다.
const fruits = ['apple', 'banana', 'cherry', 'orange', 'grape'];
// 글자 길이가 5보다 큰 아이템이 있는지 테스트
const result = fruits.filter((item) => item.length > 5);
// 테스트에 통과한 요소들을 모아 새로운 배열을 반환
console.log(result); // [ 'banana', 'cherry', 'orange' ]
형태
arr.filter(callback(element[, index[, array]])[, thisArg])
callback: 요소를 시험할 함수,
true 를 반환하면 요소를 유지 / false 일 경우 버린다.
element: 처리할 현재 요소
index: c처리할 현재 요소 인덱스 [Optional]
array: filter()를 호출할 배열 [Optional]
thisArg: callback을 실행할 때 this로 사용되는 값 [Optional]
반환 값
배열의 각 요소들에 대해 실행한 callbak의 테스트에 통과한 요소들을 모아 새로운 배열을 반환한다.
어떤 요소도 테스트를 통과하지 못한다면 빈 배열을 반환한다.
const fruits = ['apple', 'banana', 'cherry', 'orange', 'grape'];
// 글자 길이가 5보다 큰 아이템이 있는지 테스트
const result = fruits.filter((item) => item.length > 5);
// 테스트에 통과한 요소들을 모아 새로운 배열을 반환
console.log(result); // [ 'banana', 'cherry', 'orange' ]
//기존의 배열을 변형하지 않는다.
console.log(fruits); // [ 'apple', 'banana', 'cherry', 'orange', 'grape' ]