Menu
Coddy logo textTech

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); // 11
challenge icon

Challenge

Easy

Create a function called analyzeSparseArray that takes a sparse array as an argument. The function should return an object with the following properties:

  1. length: The total length of the array
  2. elementCount: The number of non-empty elements in the array
  3. largestGap: 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); // 11

Try it yourself

function analyzeSparseArray(arr) {
  // Write your code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow