Sparse Array On JavaScript
A sparse array in JavaScript is an array that contains gaps, meaning it has empty or undefined elements between indices. In JavaScript, arrays are essentially objects where the keys are indices, so you can have arrays with “missing” elements between some indices, which is referred to as being sparse.
Example of a Sparse Array:
let sparseArray = [];
sparseArray[0] = 'value1';
sparseArray[5] = 'value2';
console.log(sparseArray); // Output: ['value1', <4 empty items>, 'value2']
console.log(sparseArray.length); // Output: 6
console.log(sparseArray[4]); // Output: undefinedExplanation:
- Initial Array:
- sparseArray is initially an empty array [].
- Adding Element at Index 0:
- sparseArray[0] = ‘value1’; adds ‘value1’ at index 0. The array is now [‘value1’].
- Adding Element at Index 5:
- sparseArray[5] = ‘value2’; adds ‘value2’ at index 5. The array now has a gap between indices 1 and 4. The array looks like: [‘value1’, <4 empty items>, ‘value2’].
- Array Length:
- The length property of the array is 6, which is 1 greater than the highest index (5). The gap between index 1 and 4 doesn’t contain any defined values but still contributes to the length.
- “Empty Items”:
- When you log a sparse array, you’ll see placeholders for “empty” or undefined elements. In this case, there are 4 empty items between index 0 and index 5.
Characteristics of Sparse Arrays:
- Empty Indices: Sparse arrays can have missing elements. The missing slots are considered
undefined, but they don't explicitly storeundefinedvalues. - Length: The length of a sparse array is determined by the highest index, not by the actual number of defined elements.
- Performance: Sparse arrays may be less efficient compared to dense arrays (not have a gap or empty elements ) because of how they are stored internally.
Example of Iterating Over a Sparse Array:
When you iterate over a sparse array using forEach or map, empty slots are skipped:
sparseArray.forEach((value, index) => {
console.log(`Index ${index}: ${value}`);
});
// Output:
// Index 0: value1
// Index 5: value2As you can see, the forEach method only iterates over indices that have defined values and skips the empty slots (1 to 4 in this case).
Get Emad Mohamed’s stories in your inbox
Join Medium for free to get updates from this writer.
But you iterate over a sparse array using for , empty slots are not skipped:
for (let index = 0; index < sparseArray.length; index++) {
sparseArray[index];
console.log(`Index ${index}: ${sparseArray[index]}`);
}
// Output:
// Index 0: value1
//Index 1: undefined
//Index 2: undefined
// Index 3: undefined
// Index 4: undefined
// Index 5: value2







