Hase134
Hase134

Reputation: 15

How to use javascript filter function

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;

Upvotes: 0

Views: 150

Answers (2)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276286

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 })

Upvotes: 2

tom.alexander
tom.alexander

Reputation: 219

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

Upvotes: 0

Related Questions