참고자료 | Mdn Array.prototype.filter()
arr.filter(callback(element[, index[, array]])[,thisArg])
callback
- 테스트가 true
이면 요소를 유지하고 false
이면 버린다.
매개변수 3가지
element
: 처리할 현재 요소
index
: 처리할 현재 요소의 인덱스 (선택사항)
array
: filter
를 호출할 배열 (선택사항)
thisArg
: callback
을 실행할 때 this
로 사용하는 값 (선택사항)
filter()
는 호출되는 배열을 *변화(mutate)시키지는 않는다.
function isBigEnough(value) {
return value >= 10;
}
const filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// console.log(filtered)
// [12, 130, 44]
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// ['exuberant', 'destruction', 'present']
// 문자열의 길이가 6보다 큰 요소들만 추출되어 새로운 배열로 반환됨
map()
과 더불어 자주 사용되는 함수이니 유용하게 사용할 것!