본문 바로가기
Tech/JS

.filter(Boolean)

by egas 2021. 7. 30.

https://github.com/mdn/yari/pull/4233/files에서 .filter(Boolean)를 보았다. 무슨 문법일까?

 

avoid possible duplicate section IDs by peterbe · Pull Request #4233 · mdn/yari

Fixes #4227 I ran out of time but I'd like to write an end-to-end test that checks this. That's why it's a Draft PR. Some good pages to test this on: http://localhost:3000/en-US/docs/W...

github.com

 

  const allIDs = new Map();
  sections
    .map((section) => section.value.id)
    .filter(Boolean)
    .map((id) => id.toLowerCase())
    .forEach((id) => {
      allIDs.set(id, (allIDs.get(id) || 0) + 1);
    });

arr.filter(Boolean)

 

이것은 아래와 같이 쓰는 것과 동등하다.

 

arr.filter( function(x) { return Boolean(x); });

 

따라서, truthy 한 값들이 filter되서 나온다. 아래 예시를 보자.

 

var a = [1, 2, "b", 0, {}, "", NaN, 3, undefined, null, 5];

console.log(a.filter(Boolean));  // [1, 2, "b", {}, 3, 5];

 

결론

falsy 값을 걸러낼때는 .filter(Boolean)!

728x90

'Tech > JS' 카테고리의 다른 글

undefined 초기화  (0) 2021.07.30
불변성 Immutability  (0) 2021.07.30
ES5 vs ES6  (0) 2021.07.30
자바스크립트 꼬리물기와 for에 관하여...  (0) 2021.05.28

댓글