Marco
Marco

Reputation: 41

How to remove empty arrays from an array of arrays?

I have an array of arrays which includes some empty arrays. Exp. [ [Name1],[Name2],[Name3],[],[] ]

I tried using shift and splice (example code given)

function RemoveEmptyArrays(){
  var NameArray = [[Name1],[Name2],[Name3],[],[]];

  for (i = 0; i < NameArray.length; i++) {
      if ( NameArray[i][0] === undefined ) {
         NameArray.splice(  i, 1 );
      }
  }
  Logger.log(arrayvals);
}

Desired Output:

[ [Name1],[Name2],[Name3] ]

Upvotes: 1

Views: 91

Answers (2)

Tanaike
Tanaike

Reputation: 201358

  • You want to retrieve from [[Name1],[Name2],[Name3],[],[]] to [ [Name1],[Name2],[Name3] ].

If my understanding is correct, how about this sample script?

Sample script:

var NameArray = [["Name1"],["Name2"],["Name3"],[],[]];
var res = NameArray.filter(function(e) {return e.length})
console.log(res)

Modified script:

If your script is modified, how about this modification?

var NameArray = [["Name1"],["Name2"],["Name3"],[],[]];

for (i = NameArray.length - 1; i >= 0; i--) { // Modified
  if ( NameArray[i][0] === undefined ) {
    NameArray.splice(i, 1);
  }
}
console.log(NameArray);

Reference:

Upvotes: 2

Paul Ghiran
Paul Ghiran

Reputation: 1233

A very simple way to do this is using the spread operator from ES6 and then concat.

'concat' concatenates arrays to another array, and the spread operator takes an array and passes it to a function as if they were parameters (among other things).

Here's a working fiddle

const arr = [['a', 'b', 'c'], ['d', 'e', 'f'], [] ,[]] ;

const result = [].concat(...arr)

console.warn(result);

Upvotes: 1

Related Questions