Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- dot notation
- 스프린트 리뷰
- local scope
- 코플릿
- 슈도코드
- supertest
- TIL
- version control system
- for of
- Jest
- global scope
- package.json
- for in
- includes
- 2번째 페어
- HTML 태그 모음
- Bracket Notation
- nvm 설치
- javascript 기초
- foreach
- Splice
- npm 설치
- 코드스테이츠 1일차
- 호이스팅
- immutable
- indexof
- 코딩게임
- testbuilder
- JavaScript Runtime
- node 설치
Archives
- Today
- Total
Honey-Programming
filter 메소드 본문
# filter (조건에 따라 요소들을 걸러내기)
: callback Function으로 테스트 하여 통과하면 새로운 배열을 만든다
원본 배열은 바뀌지 않고 새로운 배열을 만든다. (immutable)
문법 : filter(callback(element[, index [, array]])[, thisArg])
callback: 각 요소를 시험할 함수(테스트를 통과하지 못한 배열 요소(false)는 버리고 새로운 배열에 포함되지 않는다.)
- element: 처리할 현재 요소
- index : 처리할 현재 요소의 인덱스
- array : filter를 호출한 배열
thisArg : callback 실행할 때 this 값
반환값 : callback 함수의 테스트를 통과한 요소로 이루어진 새로운 배열
테스트를 하나라도 통과하지 못했다면 빈 배열로 반환
- 5의 배수인 정수만 filter
let arr = [4, 15, 377, 395, 400, 1024, 3000];
let arr2 = arr.filter(function (n) {
return n % 5 === 0;
});
// 4, 377, 1024는 n % 5 === 0 즉, 5의 배수의 조건에 false 하므로 버린다.
console.log(arr2); // [15, 395, 400, 3000]
- 5의 배수에 만족하는 요소(filter)가 없을때 => 빈배열
var arr = [4, 377, 1024];
var arr2 = arr.filter(function (n) {
return n % 5 == 0;
});
console.log(arr2); // []
- 5의 배수만 구해서 각 요소를 2배 => filter로 5의 배수를 구한 후에 map으로 각 요소에 2배 적용
filter에서 5의 배수가 없을경우 map의 메소드가 의미가 없이 위에 예제와 똑같이 빈 배열로 나온다.
let arr = [4, 15, 377, 395, 400, 1024, 3000];
let arr2 = arr.filter(function (n) {
return n % 5 == 0;
}).map(function (n) {
return n * 2;
});
console.log(arr2); // [30, 790, 800, 6000]
'JAVASCRIPT' 카테고리의 다른 글
reduce 메소드 (0) | 2020.07.23 |
---|---|
map 메소드 (0) | 2020.07.23 |
forEach 메소드 (0) | 2020.07.22 |
slice, splice, split 메소드 (0) | 2020.07.22 |
immutable vs mutable (0) | 2020.07.21 |
Comments