JavaScript: Sparse Array
What is a sparse array?
When a array's numerical property key does not exist for index in the
range from 0 to n-1 (where n is the value of the property length
.
[see Array.prototype.length]
)
What is the value of missing index in a sparse array?
It doesn't exist, therefore has no value.
Note, it is different from having values of undefined .
If you access non-existent index, JavaScript return undefined .
Remember, array indexes are Property Keys of non-negative integers, all are string type.
How to Check Missing Keys?
- Use Object.keys to see a list of existing indexes.
- Use Object.prototype.hasOwnProperty to check a specific index.
// use Object.keys to see existing indexes const xx = [3, 4, 5]; delete xx[1]; console.log(Object.keys(xx)); // [ "0", "2" ]
// use hasOwnProperty to check if a index exist const xx = [3, 4, 5]; delete xx[1]; console.log(xx.hasOwnProperty("1") === false);
How to create a sparse array?
Sparse array is created when you call Array(n)
, where n is a positive integer. [see Array Constructor]
Array becomes sparse when you use βdeleteβ Operator to delete a element.
// using delete operator results a sparse array const xx = ["a", "b"]; delete xx[0]; console.log(xx.length === 2); console.log(xx.hasOwnProperty("0") === false);
Array becomes sparse when you set array property length to a number bigger than the index of last item.
Array becomes sparse when a new element is added with index greater than 1 from the last item's index. For example: const xx=["a","b"]; xx[9]="z";
// Example of a sparse array, by adding a item with index greater than length const xx = ["a", "b"]; console.log(xx.length === 2); xx[9] = "xyz"; // now xx is sparse array console.log(xx.length === 10); console.log(xx.hasOwnProperty("3") === false);
What is the use of sparse array?
Generally, there is no use. Whenever you think spare array is useful, just use a object, or use Map Object or Set Object .