JS: Sparse Array

By Xah Lee. Date: . Last updated: .

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

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

JavaScript. Array