Search code examples
javascriptarraysfor-loopfilterprototype

How to filter every element except first in an array? JS


I have a 2D array which looks like this:

numbers = [[], [1,2,4], [], [1,2,6], []];  //Not always the same

Is it possible to use prototype.filter() to erase every empty array, except the first array in the index (numbers[0])? So far, haven't found an answer.

If not, should i use a for loop or there's another prototype function i'm not aware of?


Solution

  • This should do the trick

    numbers.filter((subArray, index) => subArray.length > 0 || index === 0);