How to filter Object using Array.prototype.filter?

后端 未结 6 1653
夕颜
夕颜 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:28

    You seem to want to filter an array for elements with a certain type. Pass an appropriate function to filter:

    array.filter(istype("String"))
    

    You just need to write istype now:

    function istype(type) {
      return function(x) {
        return Object.prototype.toString.call(x) === '[object ' + type + ']';
      }
    }
    

    You seem to have thought you could filter for numbers by saying filter(Number) etc. But that will not work. Number is just another function, which tries to turn something into a number (not check if it's a number). Then, filter filters the array depending on whether the result is truthy or falsy. Number will produce a truthy value for any non-zero number obviously, and true. For a string, or an object, or pretty much anything else, it will return NaN, which is falsy, with odd exceptions such as returning 0 for [] or an all-blank string.

    Same with string. String is just another function, which tries to turn something into a string. Then, filter filters the array depending on whether the result is truthy or falsy. String will produce a truthy value for almost anything other than a non-empty string.

    This has nothing whatsoever to do with destructuring; why would you think it does? You might want to remove that unfortunate part of your post. Nor is it clear what you mean by "calling filter without a callback"--using a callback to determine which elements to filter in and out is the entire DNA of filter. It is also unclear what pattern you are referring to when you say function(prop, value) { } pattern.

    At the end of your question, you ask two specific questions:

    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 ?

    You filter objects from an input array by providing a function which determines if a particular element is an object. That is not what the object prototype or constructor Object is, so that won't help you. You have to write a little function to pass to filter, that's how it works. It could be anonymous, or it could be defined elsewhere and passed in

    How to filter specific objects within an array passed to Array.prototype.filter() by passing property name or value to match object without using anonymous function callback pattern ?

    What do you mean by "passing property name or value to match object"? Do you mean, filter out elements which are missing a particular property name or value? Then write a function to do that. There is no built-in function for this purpose, if that is what are looking for.

提交回复
热议问题