728x90

✨ 내가 제공한 function통과(pass)하는 값(element)들을 새로운 배열로 만들어주는 helper method

💻Example Code

ex1)
const originArr = [ 1, 2, 3, 4, 5 ];
const passedArr = originArr.filter( num => num !== 3 );

console.log(originArr);
console.log(passedArr);

실행 결과(3이 없어진 배열이 새로 생긴 것을 볼 수 있다)

ex2)
const originArr = [ 'a', 'b', 'c', 'd', 'e' ];
const passedArr = originArr.filter( char => char !== 'a' );

console.log(originArr);
console.log(passedArr);

실행 결과('a'가 제거된 것을 볼 수 있다)

😋 배열에서 내가 원하지 않는 값을 제거하고(솎아내고) 새로운 배열을 생성한다.
map()과 마찬가지로 정말 정말 많이 쓰인다. 꼭 알아둬야할 helper다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

 

Array.prototype.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Math.random()  (0) 2020.01.18
Math.ceil()  (0) 2020.01.18
Array.prototype.map()  (0) 2020.01.11
Array.prototype.push()  (0) 2020.01.06
Array.prototype.pop()  (0) 2020.01.04

+ Recent posts