Skip to content

Instantly share code, notes, and snippets.

@yano3nora
Last active March 27, 2022 12:25
Show Gist options
  • Save yano3nora/24a54d8c7e96a6df24464b872a719be7 to your computer and use it in GitHub Desktop.
Save yano3nora/24a54d8c7e96a6df24464b872a719be7 to your computer and use it in GitHub Desktop.
[js: Filter falsy from Array] #js
// https://qiita.com/akameco/items/1636e0448e81e17e3646
// 普通に評価
const arr = [1, 2, 3, null, 5, undefined, false, 7]
const x = arr.filter(v => v)
console.log(x) // [ 1, 2, 3, 5, 7 ]
// Boolean ぶち込んでも良い
const arr = [1, 2, 3, null, 5, undefined, false, 7]
const z = arr.filter(Boolean)
console.log(z) // [ 1, 2, 3, 5, 7 ]
// type script だと filter(Boolean) が type safe じゃない
// https://stackoverflow.com/questions/43118692/typescript-filter-out-nulls-from-an-array
//
['', 0, undefined, null, NaN, false].flatMap(v => v ? [v] : []) // []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment