Alex Bykov Alex Bykov - 5 months ago 14
Javascript Question

Remove undefined from multidimensional array

So I need to remove empty (undefined) items from the multidimensional array. Atm my code looks like this (it's a method I run so that's why i am using

this
:

f: function(arr) {
var __ = this;
arr = arr.filter(function(item) {
return Array.isArray(item) ? __.f(item) : typeof(item) !== "undefined";
});
return arr;
}


but if i run
console.log(myObject.f([1, 2, , , , , 3, 4, [5, , , , , ], 6, , , , 8, 3, [[[], 9]]]));

i get
[ 1, 2, 3, 4, [ 5, , , , ], 6, 8, 3, [ [ [], 9 ] ] ]
and that is kinda weird result. I goes pretty well for the first layer but removes only one undefined from inner layers. Also I would like to remove a subarray that consists of no items.

Answer

How about something like this:

var arr = [1, 2, , , , , 3, 4, [5, , , , , ], 6, , , , 8, 3, [[[], 9]]];

var remove = function (array) {
  var result = [];

  array.forEach(function (item) {
    if (Array.isArray(item) && item.length!=0) {
      // Item is a nested array, go one level deeper recursively
      result.push(remove(item));
    }
    else if (typeof item !== 'undefined') {
      result.push(item);
    }
  });

  return result;
};

And then console.log(remove(arr)); gives us [1, 2, 3, 4, [5], 6, 8, 3, [[[], 9]]]

Comments