TIL.91 Javascript_Filter 함수
Filter()
배열을 순회하며 요소마다 조건 확인 후 조건을 만족하는 원소들로 구성된 새로운 배열 리턴한다
주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환합니다.
이름 그대로 요소를 걸러내는 것을 목적으로 한다.
let newArray = arr.filter(callback(currentValue[, index, [array]]) {
// return element for newArray, if true
}[, thisArg]);
반환 값
테스트를 통과한 요소로 이루어진 새로운 배열. 어떤 요소도 테스트를 통과하지 못했으면 빈 배열을 반환합니다.
parameter 눈으로 확인하기
let numbers = [1, 4, 9]
let parameters = numbers.filter((num, index, arr) =>
{console.log(num, index, arr)})
//
1 0 [ 1, 4, 9 ]
4 1 [ 1, 4, 9 ]
9 2 [ 1, 4, 9 ]
filter를 이용해 6글자 이상 문자열 출력하기
const words = ['limit', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
//
[ 'exuberant', 'destruction', 'present' ]
배열에서 5의 배수인 정수만 모아 출력하기
var arr = [4, 15, 377, 395, 400, 1024, 3000];
var arr2 = arr.filter(function (n) {return n % 5 == 0;});
console.log(arr2);
//[ 15, 395, 400, 3000 ]
콜백 함수의 리턴은 boolean을 가집니다.
리턴이 true인 요소만 모아서 새로운 배열을 만듭니다. 생략하면? 리턴은 undefined이므로 false가 됩니다.
만족하는 요소가 없다면? 빈 배열이 반환됩니다.
var arr = [4, 377, 1024];
var arr2 = arr.filter(function (n) {return n % 5 == 0;});
console.log(arr2);
// []
5의 배수만 구해서 각 요소 * 2
var arr = [4, 15, 377, 395, 400, 1024, 3000];
var arr2 = arr.filter(function (n) {
return n % 5 == 0;
}).map(function (n) {
return n * 2;
});
console.log(arr2);
// [30, 790, 800, 6000]
5의 배수가 없이 빈배열이 반환되는 상황
var arr = [4, 377, 1024]; // 5의 배수가 없음.
var arr2 = arr.filter(function (n) {return n % 5 == 0;}).map(function (n) {return n * 2;
}); // 필터로 부터 빈 배열이 반환됨
console.log(arr2);
만약 filter로부터 빈 배열이 아닌 결과 없음을 의미하는 다른 값이 반환되었다면 에러를 뿜었을 것입니다.
10이하의 모든 작은 값 걸러내기
다음 예는 값이 10 이하인 모든 요소가 제거된 걸러진 배열을 만들기 위해 filter()를 사용합니다.
function isBigEnough(value) {
return value >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered 는 [12, 130, 44]
자바스크립트의 유용한 배열 메소드 사용하기... map(), filter(), find(), reduce()
대부분의 간단한 로직은 배열로 표현이 가능하고 반복문으로 원하는 결과를 얻을 수 있습니다. 예를들어 DB에서 읽어온 거대한 데이터 리스트를 걸러내고 걸러내어 클라이언트가 원하는 모
bblog.tistory.com
developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Array.prototype.filter() - JavaScript | MDN
filter() 메서드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환합니다. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive exampl
developer.mozilla.org