Sparse Arrays
Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 49 of 65.
A sparse array in JavaScript is an array with empty slots or gaps between its elements. These gaps are created when you assign values to non-consecutive indices or when you delete elements from an array.
Here's an example of creating a sparse array:
let sparseArray = [1, , , 4, 5];
console.log(sparseArray.length); // 5
console.log(sparseArray); // [1, empty × 2, 4, 5]You can also create sparse arrays by assigning to an index beyond the current length:
let arr = [1, 2, 3];
arr[10] = 10;
console.log(arr); // [1, 2, 3, empty × 7, 10]
console.log(arr.length); // 11Challenge
EasyCreate a function called analyzeSparseArray that takes a sparse array as an argument. The function should return an object with the following properties:
length: The total length of the arrayelementCount: The number of non-empty elements in the arraylargestGap: The size of the largest gap (consecutive empty slots) in the array
Cheat sheet
A sparse array is an array with empty slots or gaps between elements, created by assigning values to non-consecutive indices or deleting elements.
Creating sparse arrays with gaps:
let sparseArray = [1, , , 4, 5];
console.log(sparseArray.length); // 5
console.log(sparseArray); // [1, empty × 2, 4, 5]Creating sparse arrays by assigning beyond current length:
let arr = [1, 2, 3];
arr[10] = 10;
console.log(arr); // [1, 2, 3, empty × 7, 10]
console.log(arr.length); // 11Try it yourself
function analyzeSparseArray(arr) {
// Write your code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String FundamentalsIterate Over StringsTemplate LiteralsString MethodsRecap - String Weaver4JSON Part 2
Iterate Over JSONNested JSONJSON Optional ChainingShallow And Deep CopyRecap - Bicycle ShopRecap - Solar System10Manage Festival System
Project OverviewAdd Movies & Venues2Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays5Sets Part 1
What Is A Set?Iterating Over SetsAdding An ElementRemoving An ElementChecking If An Element ExistsSize And Is EmptyCopy And ClearRecap - Basic Of Sets8Arrays Interesting Topics
Array DestructuringSpread Syntax in ArraysSparse ArraysRecap - Arrays Workshop3JSON Part 1
What is a JSON?Check If Key ExistsObject MethodsThe Spread Operator Part 1The Spread Operator Part 2Remove KeysRecap - JSON Manipulate Keys