filter(Boolean)를 활용한 JS 배열 관리

yb·2021년 5월 26일
5

WEB

목록 보기
3/3

CRA(create-react-app) 프로젝트를 eject하여 소스를 분석하던 도중 신기한 소스를 발견했다.

const something = [
 ...some
].filter(Boolean);

왜 이렇게 사용할까?

JS에서 제공되는 배열은 아래와 같이 선언하여 사용할 수 있다.

const bad = undefined;
const bomb = [undefined, 5, null, ,,undefined];


const arr = [bad, 1, 2, ...bomb];
// arr = [undefined, 1, 2, undefined, 5, null, undefined, undefined, undefined]

위에서 제공되는 예시와 같이 undefined 또는 null이 의도하지 않게 들어갈 수 있다.

이러한 가능성은 반복문에서 문제가 발생될 가능성이 크다.

arr.map((item) => {
  console.log(item.value);  // ERROR! Uncaught TypeError: Cannot read property 'item' of undefined
})

이를 해결하기위해 일반적으로 반복문 내에서 체크하는 로직을 삽입하여 처리하기도 한다.

arr.map((item) => {
  if (item) {
    return item;
  }
  
  console.log(item.value);
})

하지만 이러한 처리방식은 두가지의 문제점을 야기한다.

  1. 코드가 복잡해진다.
  2. 배열이 또다른 새로운 배열로 확장되는 경우 또는 배열이 재사용되는 경우 동일하게 체크하는 로직을 삽입하여야한다.

이보다 더 좋은 방법은 없을까?

그 방법이 filter(Boolean)을 사용하여 배열을 믿을 수 있는 상태로 만드는 것이다!

심플하고 간단하게 사용할 수 있다.

let array = [false, 0, -0, 0n, "", null, undefined, NaN, {hello: "world"}];

console.log(array.filter(Boolean)); // [{hello: "world"}]

Booleaniterator 로 사용하여 false, 0, -0, 0n, "", null, undefined, NaN를 제거할 수 있다.

Reference
https://michaeluloth.com/filter-boolean

0개의 댓글