JS: 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 (where n+1 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 .
π WARNING: Array.prototype.map and others skip missing indexes.
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.
- 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. e.g.
const x=["a"]; x[9]="z";
// 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);
// 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 .