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 existing array indexes.
const arr = [3, 4, 5]; delete (arr[1]); console.log( Object.keys(arr), ); // [ "0", "2" ]
How to create a sparse array?
- 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. For example:
const aa=["a","b"]; aa[9]="z";
- Sparse array is created when you call
Array(n)
, where n is a positive integer. [see Array Constructor]
What is the use of sparse array?
Generally, there's no use. Whenever you think spare array is useful, just use a object, or use Map Object or Set Object .
Sparse Array Examples
// using delete results a sparse array const rr = ["a", "b"]; delete rr[0]; console.log(rr.length === 2); // true console.log(rr.hasOwnProperty("0") === false); // true console.log(rr); // [ 'a', <1 empty item> ] console.log( Reflect.ownKeys(rr), ); // [ '0', 'length' ]
// Example of a sparse array, by adding a item with index greater than length const cc = []; cc[2] = "b"; // now cc is sparse array console.log(cc); // [ <2 empty items>, 'b' ] console.log(cc[0]); // undefined console.log(cc[1]); // undefined console.log(cc[2]); // b console.log(cc.length); // 3 console.log( Reflect.ownKeys ( cc ) ); // [ '2', 'length' ]