Tech/JS
.filter(Boolean)
egas
2021. 7. 30. 22:02
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