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

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' ]

JavaScript Array

βˆ‘ JS in Depth
XAH Β BUY NOW

JS in Depth

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc