0

I am running the code below in chrome's console. I would like filteredArr to contain 3 objects however I am getting the empty {} as a fourth. The idea is to filter through the flags array and return objects with key == true(or === true - not sure which one works) and the values of true keys append to filteredArr. Any help is appreciated!

var flags = [ { usa: ["red", "white", "blue"] }, null, { germany: ["red", "yellow", "black"] }, {}, { jamaica: ["green", "yellow", "black"] }, "", undefined];

var filteredArr = flags.filter(function(val) {

    return !(val === "" || typeof val == "undefined" || val === null || typeof val == "null");
});

filteredArr;

3
  • 7
    this code almost gives me a headache. Commented Aug 14, 2014 at 21:34
  • 1
    typeof val == "null" can be removed since typeof null === "object" Commented Aug 14, 2014 at 21:35
  • 1
    Is this what you need .filter(function(val){return !!val && Object.keys(val).length}) Commented Aug 14, 2014 at 21:36

2 Answers 2

2

First of all, if you want to filter falsy bits, filter on Boolean:

var filteredArr = flags.filter(Boolean)

Which produces the same result as your code but more elegantly. Now if you want to filter objects without enumerable keys you can use Object.keys:

var filteredArr = flags.filter(Boolean).
                        filter(function(el){ return Object.keys(el).length })

Alternatively:

var filteredArr = flags.map(Object).
                        filter(function(x){ return Object.keys(x).length })

Or, flattened into a single filter:

var filtered =  flags.filter(function(x){ return Object.keys(Object(x)).length })
Sign up to request clarification or add additional context in comments.

8 Comments

Ah, beat me by one sec.
I know its trivial in this example, but each filter is going to loop through the list right? basically twice...
@elclanrs Sorry, happens to me all the time too. Thanks for the edit :)
@PSL Yes. Though in terms of performance, it would be advisable to use a for loop rather than .filter since no engines will optimize that closure away which is expensive here. In terms of iteration count - with the current implementation it will iterate the list twice, however in future versions there will be ways around it (cast into a generator - then chain to generators, effectively iterating the array zero times and performing no actions until it is iterated).
@BenjaminGruenbaum that will be awesome.. :)
|
0

An empty object is not null. You'll need to check if an object is empty via something like this:

Object.keys(obj).length === 0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.