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 JavaScript: Array.prototype.length

What is the value of missing elements in a sparse array?

It doesn't exist, therefore has no value.

If you access it (For example, myarray[3] where property key "3" doesn't exist), it has a value of undefined, just like accesing a non-existent property of a object.

Remember, array indexes are property keys of "0" and positive integer, all are string type.

〔►see JavaScript: Property Key

What is the effect of sparse array?

When array is sufficiently sparse (missing lots indexes), it loses its special efficiency when accessing array by indexes. In performance, it effectively is like a hashtable.

How to create a sparse array?

In general, you should never use sparse array. Just use a normal object if necessary.

Array can become sparse in a number of ways.

Do not do any of the above. To add or remove elements, use array methods. 〔►see JavaScript: Array.prototype

What is the use of sparse array?

Generally, there's no use. It has some use if you are doing sparse matrix in math. (matrix as array of array) That is, a huge matrix with most elements being 0. Using spare array saves storage space. (but in this case, you can use object too.)

If you are doing math of sparse matrix, you should use a dedicated library instead.

Example of Sparse Array

// delete operator results a sparse array

// using delete to remove last item
var rr = ["a", "b"];
delete rr[1];

console.log(rr.length); // 2
console.log(rr); // [ 'a', ]
// Example of a sparse array, by adding a item with index greater than 1 than the last item's index.
var cc = [];
cc[2] = "b"; // now cc is sparse array

console.log(cc); // [ , , 'b' ]
console.log(cc[0]); // undefined
console.log(cc[1]); // undefined
console.log(cc[2]); // b
console.log(cc.length); // 3

Array Topic

  1. JavaScript: Array Basics
  2. JavaScript: Understand JS Array
  3. JavaScript: Create Array
  4. JavaScript: Sparse Array
  5. JavaScript: Array-Like Object
  6. JavaScript: Array How-To

  1. JavaScript: Array Object
  2. JavaScript: Array.prototype
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.