How to remove empty elements in a multidimensional array using Javascript

Viewed 1025

Beginner programmer here that is trying to build a tool to make my life easier. I am able to pull data from a Google sheet, but it comes out looking like the bellow array with a lot of empty elements both in the elements I want to capture (Person, Person2, etc.) and around them. This is due to how the sheet is formatted and I won't be able to remove the empty cells around it.

var array = [[Person1,, Age1,, Address1], [,,,,], [Person2,, Age2,, Address2], [,,,,] ...]

I assume there is an easy way to filter through the array and remove the empty/null items. But my attempts to use .filter() and nested for loops have not worked. Can anyone help on the best way to get a multidimensional array without the empty items?

2 Answers

you can use reduce function and remove items which are either null or array with zero length

var arr = [["Person1", null, "Age1", null, "Address1"]
  , [null, null, null, null, null]
  , ["Person2", null, "Age2", null, "Address2"],
[null, null, null, null, ["t"]]]

function reducer(res, item) {
  if (!item) return res;
  if (Array.isArray(item)) {
    var obj = item.reduce(reducer, [])
    if (obj.length > 0) {
      res.push(obj)
    }
    return res;
  }
  res.push(item);
  return res;
}

var res = arr.reduce(reducer , [])
console.log(res)

Fortunately you have just a 2D array, which is a list of 1D arrays.

Let's start with an 1D array:

var row = ['a','b',,'c',,];


// via a loop:

var new_row = [];
for (cel in row) if (row[cel]) new_row.push(row[cel]);

console.log(new_row); // ['а', 'b', 'c']


// via a filter() function:

var new_row_f = row.filter((cel) => cel);

console.log(new_row_f); // ['a', 'b', 'c']

Here is a 2D array:

var table = [['a1','b1',,'c1',,],[,,,,,],['a2','b2',,'c2',,]]


// via nested loops:

var new_table = []
for (var row=0; row<table.length; row++) {
    var new_row = [];
    for (var cel=0; cel<table[row].length; cel++) {
        var new_cel = table[row][cel];
        if (new_cel) new_row.push(new_cel);
    }
    if (new_row.join("")!="") new_table.push(new_row);
}

console.log(new_table); // [ [ 'a1', 'b1', 'c1' ], [ 'a2', 'b2', 'c2' ] ]


// via a chain of filter() & map(filter()) functions:

var new_table_f = table.filter(row => row.join("") != "")
                       .map(row => row.filter((cel) => cel));

console.log(new_table_f); // [ [ 'a1', 'b1', 'c1' ], [ 'a2', 'b2', 'c2' ] ]

Related