본문 바로가기
Study/Vanila JS

[Javascript][개념정리] Array.filter()

by 22정민 2023. 1. 12.

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

 

Array.prototype.filter() - JavaScript | MDN

filter() 메서드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환합니다.

developer.mozilla.org

filter()메서드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아서 새로운 배열로 반환

ex)

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"]

- filter()메서드에 의해 word length가 6보다 긴 word만 배열로 출력되었다.

- 괄호 안에는 함수가 들어간다.

 

구문

  arr.filter(callback(element[, index[, array]])[, thisArg])

- 매개변수 2가지(callback, thisArg)

1. callback : 각 요소를 시험할 함수 -> true반환 시 요소를 유지 / false반환 시 요소 버림

<callback의 매개변수>

=> (1) element : 처리할 현재 요소

=> (3) index : 처리할 현재 요소의 인덱스

=> (4) array : filter를 호출 한 배열

2. thisArg : callback실행 시 this로 사용하는 값

 

[활용] 프로그래머스 각도기 문제

function solution(angle) {
    return [0, 90, 91, 180].filter(x => angle>=x).length;
}

(예각=1, 직각=2, 둔각=3, 평각=4)

.length는 배열의 길이를 물어보는 것

 

따라서,

0>=x : 1,

90>=x : 2,

91>=x: 3,

180>=x: 4

이다