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>
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>
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
👉 ANOTHER useful JavaScript method. Do you know you can remove all commas from a JavaScript array using the join() method. Check this post..
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>
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.