Yoon.s

[javascript] filter 함수 본문

프론트/Javascript

[javascript] filter 함수

yo_onHJ 2020. 9. 7. 21:53

프로그래머스 문제를 풀다가 배열에서 새로운 배열로 값을 이동시키고 싶은데 

동일한 개수에 동일한 순서로 넣을때는 map을 사용하면 쉽게 새로운 배열에 값을 저장할 수 있지만, 

조건에 맞는 값만 새로운 배열에 저장하려면 다른 함수를 사용해야 한다는 것을 깨달았다. 

 

또한, map함수의 경우 조건을 주게되면 true/false 값을 리턴함
arr=[4, 2, 1] 이라면, arr.map(x=>x>2)  //[true, false, false] 

 

그래서 내가 생각했던 함수는 array.push였다. 

하지만 filter() 라는 더 좋은 함수가 있었다. 

 

 

filter()

: 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환

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

단어의 길이가 6보다 작은 엘리먼트만 새로운 배열인 result에 담겠다! 

 

 

참조사이트.

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

Comments