1

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] ]

2 Answers 2

2
  • 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:

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.