DEV Community

Cover image for Javascript sparse array and how to avoid them
Isabelle M.
Isabelle M.

Posted on

Javascript sparse array and how to avoid them

Sparse arrays are arrays with elements that are not consecutive and don't always start at index 0. In other words, the length property of the array does not match the number of elements in the array and it contains empty indexes. This is not a problem in itself, but it can lead to unexpected results.

How to create a sparse array

Sparse arrays can be created by initializing an array with the Array() constructor or when a value is assigned to an index that is greater than the current length of the array.
For example, if you have an array with 3 elements and you assign a value to the 4th index, the array will become sparse.

const arr = [1, 2, 3];
arr[4] = 4; // [1, 2, 3, <1 empty item>, 4]
Enter fullscreen mode Exit fullscreen mode

Similarly, if you increase the length of the array, the array will become sparse.

const arr = [1, 2, 3];
arr.length = 5; // [1, 2, 3, <2 empty items> ]
Enter fullscreen mode Exit fullscreen mode

Another way a sparse array can be created is by using the delete operator. This will remove the element from the array, but it will leave an empty index.

const arr = [1, 2, 3];
delete arr[1]; // [1, <1 empty item>, 3]
Enter fullscreen mode Exit fullscreen mode

Why can sparse arrays be a problem?

The main problem with sparse arrays is that some JavaScript methods do not handle spare arrays the same way. Meaning, that some methods will ignore the empty indexes and some will not.
For example, the Array.prototype.filter() method will ignore the empty indexes but the Array.prototype.map() method will not.

const arr = [1, 2, 3];
arr[4] = 4;
arr.map(v =>  v); // [ 1, 2, 3, <1 empty item>, 4 ]
arr.filter(() => true) // [ 1, 2, 3, 4 ]
Enter fullscreen mode Exit fullscreen mode

Note that the Array.prototype.filter() method can be used to remove empty indexes from an array.

Another reason to watch out for sparse arrays is that some array methods will convert holes to undefined and some will not.
For example, the spread operation (...) will convert holes to undefined while Array.prototype.slice() will not.

const arr = [1, 2, 3];
arr[4] = 4;
const res = [...arr]; // [1, 2, 3, undefined, 4]
const res1 = arr.slice(); // [1, 2, 3, <1 empty item>, 4]
Enter fullscreen mode Exit fullscreen mode

How to detect a sparse array

Sparse arrays can be detected by checking if the length property of the array is greater than the number of elements in the array or by using the Object.prototype.hasOwnProperty() method.

const arr = [1, 2, 3];
arr[4] = 4;
arr.length > arr.filter(() => true).length; // true
arr.hasOwnProperty(3); // false
Enter fullscreen mode Exit fullscreen mode

Top comments (0)