How to Remove Empty Slots in JavaScript Arrays

← Prev

I remember using the filter() method once to remove empty slots in an Array in JavaScript. An empty array slot might look like this … const arr = [1, , 3, 4, , 6]; (integers 2 and 5 are missing) and to remove these slots you can use arr.filter (x => x). There is a better way to do this, especially with nested arrays. I am going to show you how to remove the empty array slots using a new method called the flat().

Remove Empty Slots in Array in JavaScript

The built-in flat() method was introduced in ES2019 to flatten an array. Here’s the syntax.

Syntax flat() Method

arr.flat([depth]);

The method takes a parameter as depth. The depth level specifies how many layers of nested array should it flattened. The default value is 1. Therefore, if you do not specify any value, it will default to 1.

These two methods are same.

arr.flat()

is as good as

arr.flat(1)

Now, let's see how we can use the flat() method to remove empty array slots.

<script>
    const arr = ['a', 'b', , 'd', , 'f'];
    document.write (arr.flat());
</script>
Try it

If you see the output, it ignores the empty slots and shows the result. Ignoring the flat() method will result as a, b, , d, , f. See this code!

const arr = ['a', 'b', , 'd', , 'f'];
document.write (arr);

Note: It works on numbers (or integers) and alphabets.

Remove Empty Slots in Nested Array

If you have nested arrays and want to remove empty slots in deeper levels, all you have to do is specify an appropriate depth level to the .flat() method. For example,

<script>
    const arr = ['a', 'b', , 'd', , 'f', [[1, 2, , 5, 4]]];     // Nested array.
    document.write (arr.flat(2));         // Using flat() with depth 2.
</script>
Try it
Look carefully and you will see the .flat() method now has depth 2. Since, I have a nested array of alphabets and integers and both have empty slots. The result is amazing.

Note: You can use the value Infinity for the depth parameter, if you have multiple nested arrays. For example,

arr.flat(Infinity);

Browser Support:
Chrome 39.0 - Yes | Firefox 34.0 - Yes | Internet Explorer - No | Safari - Yes | Edge 84.0 - Yes

You may also like: How to Remove Commas from Array in JavaScript

Using .filter() Method to Remove empty Array slots

Alternatively, you can use the .filter() method in JavaScript to remove all the empty slots in array.

<script>
    const arr = ['a', 'b', , 'd', , 'f'];
    document.write (arr.filter (x => x));
</script>
Try it

This method too works on numbers (or integers) and alphabets. However, it can be difficult to make it work with nested arrays. That’s why I would recommend using the .flat() method instead. It is simple to use and you can flatten and/or remove empty slots in deep array levels.

Thanks for reading.

← Previous


Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.
Delivered by FeedBurner