Rosie, Lee 2021. 10. 6. 22:22

filter라는 메소드는 배열 데이터의 아이템들을 특정한 기준에 의해 필터링(true)해서 새로울 배열데이터로 반환해줍니다.

 

MDN의 공식 문서를 참고해보세요.

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

 

Array.prototype.filter() - JavaScript | MDN

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

developer.mozilla.org

 

필터링하여 새로운 배열을 하기 때문에, 새로운 배열을 반환합니다.

기존 배열(원본 데이터)에는 영향에 없습니다.

const nums = [1, 2, 3];

const f = nums.filter(num => {
  return num < 3
})

console.log(f);
// output -> (2) [1, 2]

console.log(nums);
// output -> (3) [1, 2, 3]

 

실행문이 한 줄 밖에 없다면, 아래와 같이 코드를 조금 더 간결하게 작성할 수 있습니다.

const nums = [1, 2, 3];

const f = nums.filter(num => num < 3)

console.log(f);
// output -> (2) [1, 2]
반응형