Open In App

Dense and Sparse Array in JavaScript

Last Updated : 06 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, an array is a data structure used for storing a collection of values. Each value in the collection is assigned a unique index number. Arrays in JavaScript can contain values of any data type, such as strings, numbers, objects, and even other arrays. In JavaScript, arrays can be of two types dense and sparse array.

Dense and sparse arrays are two important types of data structures used for organizing and accessing collections of elements. A dense array, also referred to as a contiguous array, stores elements in a sequential manner in memory, allowing for constant-time access to any element. As a result, dense arrays are well-suited for applications that require frequent access to elements or numerical computations.

On the other hand, a sparse array is a data structure designed to store mostly empty or zero elements. Sparse arrays only store non-zero or non-empty values, reducing memory usage and speeding up iteration over non-empty values. However, accessing individual elements in a sparse array can be slower than in a dense array, as it requires searching for the index of the desired element.

Dense Array: Dense arrays are the most commonly used type of array, and we all are familiar with them. In a dense array, every element is defined and has a value, meaning there are no “holes” in the array. The first element has an index of 0, the second element has an index of 1, and so on, with items existing at each index from 0 to length-1.

Syntax:

const arr_name = [item1, item2, item3, ...];

Example 1 :

Javascript




const fruits = ["mango","apple","grapes"];
console.log(fruits[0]); 
console.log(fruits[1]); 
console.log(fruits[2]); 
console.log(fruits.length);


Output

mango
apple
grapes
3

In the above example, there is an array named fruits which contains three fruits that can be accessed through their respective indexes.

Example 2:

Javascript




const denseArray = [1,2,3,4,5];
console.log(denseArray);


Output

[ 1, 2, 3, 4, 5 ]

In the above example, there is an array named denseArray which contains natural numbers from 1 to 5, as there are no gaps in the array, hence it is a dense array.

Memory Implementation Of Dense Array: In a dense array, memory is allocated as a continuous block of memory, this is called Contiguous Memory Allocation where array items are stored sequentially from index 0 to index array.length-1. The first element is stored at index 0, the second is stored at index 1, and so on. In memory, a dense array is implemented as a contiguous block of memory, where each element is stored in a fixed-size slot. The slots are allocated consecutively, so the index of an element can be used to compute its memory address directly.

When you create a dense array, JavaScript reserves a block of memory to hold the specified number of elements. Each element in the array is assigned a unique index, starting from 0 and increasing by 1 for each subsequent element.

Because dense arrays are stored in contiguous memory, accessing and modifying their elements is generally very efficient. You can use standard pointer arithmetic to compute the memory address of an element based on its index, which allows for fast random access.

Sparse Array: A sparse array may contain empty or “hole” items within it, meaning that we can skip one or multiple array items. In JavaScript, a sparse array is an array in which not all elements are defined or initialized. This means that the array may have gaps or holes where some indices have no values. However, access and modification of array elements are possible just like in a normal array.

Syntax 

const arr_name = [item1,item2, , , item3];

Example

Javascript




const sparseArray = [10, , , 40];
console.log(sparseArray)


Output

[ 10, <2 empty items>, 40 ]

Different ways to create a Sparse array:

1. Using Array Literal: You just have to skip the item which you don’t want to specify. In other words, we can also create a sparse array using the array literal syntax by omitting values for specific indices. Sparse arrays can be created using an array literal by omitting some of the elements in the array declaration. The resulting array will have “holes” where the omitted elements would have been, and those holes will be treated as undefined values.

Syntax:

const arr_name = [item1,item2, , , item3];

  Example:

Javascript




const colors = ["red","green","blue", ,"black"];
console.log(colors);


Output

[ 'red', 'green', 'blue', <1 empty item>, 'black' ]

In the above example, we omitted the value of the item at the 3rd index, so it gave an empty item as an output, we may skip array items at multiple indexes as well.

2. Using Array Constructor: With the help of an array object, we can create a sparse array using the Array constructor. It takes a single parameter as an argument which is the length of an array. To create a sparse array using the array constructor, you can specify the desired length of the array as an argument, and then set specific elements to undefined using array index notation. 

Syntax:

const arr_name = new Array(arraySize);

Javascript




const arr = new Array(5);
console.log(arr);


Output

[ <5 empty items> ]

in the above example, we specify the length of the array as 5, so it has created 5 empty items.

3. Delete any Array Item: Deleting array items from an array creates holes at those indices an empty item acts as a placeholder for them.

Syntax:

const arr_name = [item1,item2,item3];
delete arr_name[index];

Example:

Javascript




const nums = [1,2,3,4,5];
delete nums[2];
console.log(nums);


Output

[ 1, 2, <1 empty item>, 4, 5 ]

In the above example before the array was dense in nature but after deleting an empty space was created which made the array sparse array.

4. By increasing the Length of Array: Whenever we increase the length of an array, empty spaces are always created to accommodate more elements. To create a sparse array by increasing the length of an existing array, you can simply set the length property of the array to a value that is greater than its current length.

Syntax:

const arr_name = [item1,item2,item3];
arr_name.length = requiredLength;

Example:

Javascript




const even = [2,4,6,8];
even.length = 6;
console.log(even);


Output

[ 2, 4, 6, 8, <2 empty items> ]

Memory implementation of Sparse Array: Unlike dense array, sparse array may or may not be allocated memory in contiguous locations, memory may be assigned in chunks as well. A sparse array is implemented in memory as an object with numbered properties, just like a regular array. However, unlike a regular array, a sparse array only stores the indices and values of defined elements, leaving gaps for undefined elements. These gaps do not take up space in memory, but they can impact the performance of some array operations. As a result, it’s important to be mindful of the potential performance issues when working with sparse arrays and to consider alternative data structures if needed.

Conclusion: To summarize, both sparse and dense arrays are types of data structures used to organize and access collections of elements. Dense arrays, also known as contiguous arrays, store elements in a sequential manner in memory. They allow for constant time access to any element and are useful for applications that require frequent element access or numerical computations. In contrast, sparse arrays are designed to store elements that are mostly empty or zero. They only store non-empty or non-zero values, which reduces memory usage and speeds up iteration over non-empty values. However, accessing individual elements can be slower compared to dense arrays, as it requires searching for the index of the desired element.

When choosing between sparse and dense arrays, the specific requirements of the application should be considered. Factors such as the size of the data, the frequency of access, and the sparsity of the data should be taken into account. Dense arrays are suitable for applications that require fast access to all elements, while sparse arrays are better suited for applications with large, mostly empty data sets.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads