Why does Array.filter(Number) filter zero out in JavaScript?

前端 未结 9 1958
时光说笑
时光说笑 2020-12-10 00:10

I\'m trying to filter all non-numeric elements out from an array. We can see the desired output when using typeof. But with Number, it filters zero out.

Here\'s the

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 01:02

    Here is another example showing how to remove multiple indices from an Array of numbers, and dealing with the 0:

    const array = [0,1,2,3,4,5,6,7,8,9]
    console.log('init', array)
    
    const indicesToDel = [2, 3, 5, 9]
    console.log('indices to del', indicesToDel)
    
    let result = array.filter( (item, index) => !indicesToDel.includes(index) ? Number.isFinite(item) : false )
    console.log('result', result)

提交回复
热议问题