JS: Sparse Array
What is a sparse array
Sparse array is when a array's property keys are missing in the range 0 to (length -1) .
// Sparse array const xx = [3, 4, , , 5]; console.log(xx.length); // 5 console.log(Object.keys(xx)); // [ "0", "1", "4" ] console.log(xx); // [ 3, 4, <2 empty items>, 5 ]
What is the value of missing index in a sparse array
It doesn't exist, therefore has no value.
If you access non-existent index, JavaScript return undefined .
🛑 WARNING: it is different from having values of undefined .
🛑 WARNING: Array.prototype.map and others skip missing indexes.
How to Check Missing Keys
// list array indexes console.log(Reflect.ownKeys([3, 4])); // [ "0", "1", "length" ]
// check if a property key exist console.log(Object.hasOwn([3, 4], "0")); console.log(Object.hasOwn([3, 4], "1")); console.log(Object.hasOwn([3, 4], "2") === false);
Function to check for sparse array
const xah_is_sparse_array = (zarr) => !Array(zarr.length).keys().every((_, i) => Object.hasOwn(zarr, i)); // s------------------------------ // test console.assert(xah_is_sparse_array([1, , 2]) === true); console.assert(xah_is_sparse_array(Array(9)) === true); console.assert(xah_is_sparse_array([1, 2]) === false);
How to create a sparse array
- Sparse array is created when you have repeated comma in array literal expression. e.g.
[3, 4, , , 5]. - 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 you assigne a value to a index beyond length. e.g.
x[42]=1;
// 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] = 1; // now xx is sparse array console.log(xx.length === 10); // index 3 nonexistent console.log(Object.hasOwn(xx, "3") === false); // index 2 exit console.log(Object.hasOwn(xx, "2") === false);
Convert sparse array to dense array
// Array.from turns sparse array into dense array. missing index get value of undefined console.log(Array.from([3, 4, , , 5])); // [ 3, 4, undefined, undefined, 5 ] // normally console.log([3, 4, , , 5]); // [ 3, 4, <2 empty items>, 5 ]
What is the use of sparse array
there is no use.
so-called sparse array is a JavaScript language design wart.
Whenever you think spare array is useful, use Map Object or Set Object.