본문 바로가기
Javascript

Array.prototype.filter()

by 이도현 2021. 11. 9.

 

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

 

Array.prototype.filter() - JavaScript | MDN

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

developer.mozilla.org

https://www.w3schools.com/jsref/jsref_filter.asp

 

JavaScript Array filter() Method

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

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

 

반환하는 값을 원본에 덮어쓰지 않기 때문에, 원래 배열을 변환하려면 따로 처리를 해야한다.

 

filter() 메소드와 map() 메소드는 구분이 사실상 거의 동일하고, 새로운 배열로 반환한다는 점도 동일하지만, filter() 메소드는 이름에서도 보이듯 테스트를 통과하는 아이템을 필터로 걸러내는 것이라면, map()은 그냥 1:1 매핑시킨다는 점에서 차이가 있다.

 

다음 예시를 보자.

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const filter_result = words.filter(word => word.length > 6);
console.log(filter_result);
//Array ["exuberant", "destruction", "present"]

const map_result = words.map(function(word){ if(word.length > 6) return word; } );
console.log(map_result);
//Array [undefined, undefined, undefined, "exuberant", "destruction", "present"]

map()의 경우 if 문의 조건을 통과하는 것으로 적용할 수 있지만, map()의 경우는 통과를 하지 않는다고 반환되는 배열에push를 하지 않는 것이 아니라, undefined를 push하는 것을 알 수 있다.

반환되어야 하는 배열의 사이즈가 입력한 배열의 사이즈와 동일해야하고, undefined 가 배열 안에 포함되어도 상관없다고 한다면 map() 메소드를 사용하고, 반환되어야 하는 배열이 조건을 통과하는 아이템에 대해서만 push되어야 한다면 map()이 아니라, filter() 메소드를 사용하여야 한다.

 

조금 헷갈릴 수 있는 케이스를 하나 더 소개한다.

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const filter_result = words.filter(word => word.length > 6);
console.log(filter_result);
//Array ["exuberant", "destruction", "present"]

const map_result = words.map(word => word.length > 6);
console.log(map_result);
//Array [false, false, false, true, true, true]

매우 비슷하게 생긴 filter()와 map() 메소드 예시이지만, 반환되는 값은 완전히 다르다. filter()의 경우 => 이후는 조건에 해당하고, 반환하는 값은 해당 조건을 통과한 아이템이지만, map()의 경우는 word.lengh > 6 이 참인지 아닌지에 대해서 반환한다.

 

이런 메소드들은 연결하여 사용할 수도 있다. 

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const filter_map_result = words.filter(word => word.length > 6).map(word => word.length > 6);
console.log(filter_map_result);
//Array [true, true, true]

 

'Javascript' 카테고리의 다른 글

JavaScript에서 false로 인식되는 값; 거짓같은 값; Falsy  (0) 2021.11.11
Array.prototype.sort()  (0) 2021.11.10
Array.prototype.map()  (0) 2021.11.03
Array.prototype.at()  (0) 2021.11.02
JavaScript Function Parameters  (0) 2021.08.31