Blake Rivell
Blake Rivell

Reputation: 13875

Filtering out null values of object list in JavaScript

I am currently filtering out null values from an array using Object.keys and map like this:

// The ultimate goal is to get the length of my list where !== null
var length = Object.keys(myList).map(x => myList[x]).filter(x => x !== null).length;

I need to find an alternative way of doing this because in IE11 I am having issues with it. It is interfering with functionality of a 3rd party control somehow.

Any ideas?

Upvotes: 0

Views: 258

Answers (2)

gaetanoM
gaetanoM

Reputation: 42054

The Arrow functions are not supported in IE. So , the equivalent of your code is:

var myList = {'1': '1', '2': '2', '3': '3', '4': null};
var length =   Object.keys(myList).map(function (x) {
  return myList[x]
}).filter(function (x) {
  return x !== null;
}).length;

console.log(length);

Because the output of Object.keys(myList) is an array and you need only to filter elements by their vaues (not null) you may reduce all to:

var myList = {'1': '11', '2': '22', '3': '33', '4': null};
var length =   Object.keys(myList).filter(function (x) {
  return myList[x] !== null;
}).length;

console.log(length);

Upvotes: 1

Lyubomir
Lyubomir

Reputation: 20037

var length = 0

for (var i = 0; i < myList.length; i++) {
  if (myList[i] !== null) { 
     length++; 
  } 
}

In this case, the for-loop is your map and the if-condition is your filter.

Upvotes: 1

Related Questions