JS: Sparse Array

By Xah Lee. Date: . Last updated: .

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 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?

// 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 .

JavaScript Array
BUY Ξ£JS JavaScript in Depth