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 = ["cat", "dog", , , "bird"];

console.log(xx.length);
// 5

console.log(Object.keys(xx));
// [ "0", "1", "4" ]

console.log(xx);
// [ "cat", "dog", <2 empty items>, "bird" ]

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: some array methods skip missing indexes. e.g. Array.prototype.map, while newer methods fill them as if they have values of undefined. e.g. Array.prototype.fill .

How to create a sparse array

// Example of a sparse array, by array constructor
const xx = Array(3);
console.assert(Object.hasOwn(xx, "0") === false);
// Example of a sparse array, by repeated comma
const xx = [, , , "a", "b"];

console.log(xx);
// [ <3 empty items>, "a", "b" ]

console.log(Object.keys(xx));
// [ "3", "4" ]

console.log(Object.hasOwn(xx, "0"));
// false
// Example of a sparse array, by setting length
const xx = ["a", "b"];
xx[9] = 1;
// now xx is sparse array

console.assert(xx.length === 10);

// index 3 nonexistent
console.assert(Object.hasOwn(xx, "3") === false);

// index 2 exit
console.assert(Object.hasOwn(xx, "2") === false);

Convert sparse array to dense array

// convert sparse array into dense array. missing index get value of undefined
console.log(Array.from([3, 4, , , 5]));
// [ 3, 4, undefined, undefined, 5 ]

How to check for sparse array

// efficient function to check if array is sparse. fast on array with thousands elements
const xah_is_sparse_array = (zarray) => !Array(zarray.length).keys().every((_, i) => Object.hasOwn(zarray, i));

// s------------------------------
// test

console.assert(xah_is_sparse_array([1, , 2]));
console.assert(xah_is_sparse_array(Array(9)));
console.assert(xah_is_sparse_array([1, 2]) === false);

What is the use of sparse array

there is no use.

Sparse array in JavaScript was a language design mistake.