How to filter Object using Array.prototype.filter?

后端 未结 6 1657
夕颜
夕颜 2020-12-03 22:52

Given

var arr = [1,2,true,4,{\"abc\":123},6,7,{\"def\":456},9,[10]]

we can filter number items within array arr using N

6条回答
  •  囚心锁ツ
    2020-12-03 23:50

    How to filter objects with or without Object prototype or constructor within in an array passed to Array.prototype.filter() without using an anonymous function callbackpattern ?

    As per spec

    callbackfn should be a function that accepts three arguments and returns a value that is coercible to the Boolean value true or false

    Number object (function's constructor) does return NaN for bad Number conversion but String and Object constructors don't return a false value (yes, filter(Number) also filters out 0)

    var arr = [0,1,2,true,4,{"abc":123},6,7,{"def":456},9,[10]];
    arr.filter(Number); //outputs [1, 2, true, 4, 6, 7, 9, Array[1]]
    

    You can create a customer function OBJ,

    function OBJ(value,index,arr){ return typeof value === "object" && !Array.isArray(value) }
    

    or Arrays are also welcome in the resultset then remove the Array.isArray check

    function OBJ(value,index,arr){ return typeof value === "object" }
    

    when used with

    arr.filter(OBJ); //outputs [{"abc":123},{"def":456}]
    

提交回复
热议问题