Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What are Special Arrays in JavaScript?
3.
Why do we Use Special Arrays in JavaScript?
4.
Types of Special Arrays in JavaScript
4.1.
Typed Arrays
4.2.
Array-like Objects
4.3.
Immutable Arrays
4.4.
Sparse Arrays
4.5.
Multidimensional Arrays
5.
Advanced Array Methods
6.
Frequently Asked Questions
6.1.
How are typed arrays different from regular arrays?
6.2.
Give an example of using an array-like object.
6.3.
How can sparse arrays be useful?
7.
Conclusion
Last Updated: Mar 27, 2024
Medium

Special Arrays in JavaScript

Author Tashmit
0 upvote

Introduction

As we know, arrays are one of the Data Structures that helps us to store data. Similarly, in JavaScript, special arrays are special extensions of arrays. 

Special Arrays in JavaScript

In this article, we will study about the special arrays in JavaScript, why we use them, and all the types of special arrays with code samples.

What are Special Arrays in JavaScript?

Arrays are a built-in data structure in JavaScript. It is used to store data values such as integers, strings, objects, or other arrays as well. Special arrays are an extension of arrays.

They have special properties and characteristics that can manipulate data. Let us see why we need to use special arrays in JavaScript.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Why do we Use Special Arrays in JavaScript?

There are many types of special arrays in JavaScript that are used for various purposes. 

  • Performance: The typed arrays work with binary data and give an optimized performance for numerical computations. 
     
  • Efficiency in memory: The typed arrays require less memory and utilize a fixed-size buffer. This results in a more efficient memory allocation than JavaScript arrays.
     
  • Flexibility with data structures: The sparse arrays allow arrays with empty slots which allows flexibility in the data structure.

Types of Special Arrays in JavaScript

In JavaScript, there are many types of special arrays that can be used. Let us see all the types of special arrays in detail.

Typed Arrays

The Typed arrays work with the binary data efficiently. It offers fixed-size arrays to store values like Int8Array, Uint8Array, Float32Array, etc. The typed arrays are used for data manipulation, multimedia processing, and game development. Let us see a code snippet to understand it better.

Code

// Creating a typed array
const uint8Array = new Uint8Array([10, 20, 30, 40]);


// Accessing elements in the typed array
console.log(uint8Array[0]);
console.log(uint8Array[1]);


// Modifying an element in the typed array
uint8Array[2] = 50;
console.log(uint8Array); 


// Getting the length of the typed array
console.log(uint8Array.length);


Output

Output

Explanation

In the above code snippet, we created a typed array. The Unit8Array stores the values 10, 20, 30, and 40. Then we appended 30 with 50 and printed the array.

Array-like Objects

The array-like objects do not have all the properties of an array. It basically an object that resembles the arrays and has a numeric index and a length property. The Array-like object includes the arguments object within a function and certain DOM collections like NodeList and HTMLCollection. Let us understand array-like objects with a sample code

Code

function printItems(obj) {
  console.log(obj.length); // Accessing the length property
  for (let i = 0; i < obj.length; i++) {
    console.log(obj[i]); // Accessing elements using numeric indices
  }
}
// Using the arguments object as an array-like object
function sum() {
  let total = 0;
  for (let i = 0; i < arguments.length; i++) {
    total += arguments[i];
  }
  return total;
}
printItems('Ninja'); 
printItems([1, 2, 3, 4]);
console.log(sum(1, 2, 3)); 


Output

Output

Explanation

In the above code, the printItems function takes an object and treats it as an array-like object. The length property is used to find the number of elements and iterate over the object using a for loop.

Immutable Arrays

JavaScript does not support immutable arrays. But a library called immutable.js offers a data structure that enables us to have immutable arrays. It ensures the data integrity by not allowing a change in arrays. Let us understand it with the help of code.

Code

​​<!DOCTYPE html>
<html>
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/4.0.0-rc.12/immutable.js"></script>
</head>
<body>
  <script>
    // Creating an immutable array
    const immutableArray = Immutable.List([10, 20, 30, 40]);


    // Adding an element to the immutable array
    const newArray = immutableArray.push(50);


    console.log("Updated Array: "+ newArray.toArray()); 
  </script>
</body>
</html>


Output

We can check the output of the above code on in the browser’s console.

Output

Explanation

In the above code, we used the immutable.js library in the script tag. With this, we were able to push an element in the array.

Sparse Arrays

The Sparse arrays have holes or empty slots in them. This allows us to skip indexes or explicitly assign undefined values. Sparse arrays are very useful to save memory and use the memory more efficiently. Let us see an example to understand it better.

// Creating a sparse array
const sparseArray = [];
sparseArray[0] = 'Greetings';
sparseArray[2] = 'Coding';
sparseArray[4] = 'Ninja';


// Accessing elements in the sparse array
console.log(sparseArray[0]);
console.log(sparseArray[1]);
console.log(sparseArray[2]);
console.log(sparseArray[3]);
console.log(sparseArray[4]);


// Iterating over the sparse array
sparseArray.forEach((element, index) => {
  console.log(`Index: ${index}, Element: ${element}`);
});


// Checking the length of the sparse array
console.log(sparseArray.length);


Output

Output

Explanation

In the above code, we created a sparse array by setting values to a specific index and leaving other indexes empty. The indices 0, 2, and 4 are explicitly assigned values, while the indices 1 and 3 remain undefined, creating empty slots in the array.

Multidimensional Arrays

In JavaScript, multidimensional arrays are not suppoted. But with the help of special arrays we can create multidimensional arrays in JavaScript as well. We can do that by creating array of arrays. Let us understand it with the help of a code snippet.

Code

// Creating a 3D array (2x2x2)
const cube = [
 [
   [1, 2],
   [3, 4]
 ],
 [
   [5, 6],
   [7, 8]
 ]
];
for (let i = 0; i <= cube.length; i++) {
   console.log(cube[i]);
}
console.log("The element present at 1st row and 1st column is: "+cube[1][0][1]);


Output

Output

Explanation

In the above code, we created an array of arrays and printed the element present at 1st row and 1st column. Hence the output is 6.

Advanced Array Methods

In JavaScript, apart from special arrays, there are some advanced array methods as well. They are used to transform and manipulate the arrays. 

  • map(): The map function is used to callback an existing array. It returns an array with the same length with the updated values of each element.
     
  • filter(): The filter function is used to filter out some elements based on a specific condition. It creates and returns a new array with the required elements.
     
  • reduce(): The reduce function is used to reduce a given array to a single value. It can be used to sum all elements. 
     
  • forEach(): The forEach function does a specific task for all the elements present in an array. For example if we want to increase all the elements by 2, we can use the forEach function. It will iterate through all elements and increase their value by 2.


Let us understand all the advanced array methods with the help of an example.

Code

const numbers = [1, 2, 3, 4, 5];


// Using map() to double each number
const doubledNumbers = numbers.map((num) => num * 2);
console.log("The doubled array is: "+doubledNumbers);


// Using filter() to get even numbers
const evenNumbers = numbers.filter((num) => num % 2 === 0);
console.log("The even numbers in array are: "+evenNumbers);


// Using reduce() to calculate the sum of numbers
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log("The sum of all elements of array is: "+sum);


// Using forEach() to print each number multiplied by 2
console.log("Double of array is: ")
numbers.forEach((num) => {
 console.log(num * 2);
});


Output

Output

Explanation

In the above code, first we used the map function to double all the elements of the array. Then we used filter function to filter out all the even numbers from the array. 

Following that, we used the reduce function to reduce the array to find the sum of all the elements. Finally, we used the forEach function to print the double of all elements of the array.

Frequently Asked Questions

How are typed arrays different from regular arrays?

Typed arrays provide fixed-size, typed arrays of numeric values. They offer more efficient storage and manipulation of binary data compared to regular arrays, which can store any type of data.

Give an example of using an array-like object.

One of the most common examples of an array-like object is the arguments object within a function. It allows access to the arguments passed to a function as if they were elements of an array, even though it lacks some array methods.

How can sparse arrays be useful?

Sparse arrays allow us to have empty slots between elements. This can save memory when we don't require consecutive indexing. They are useful when we need to store data sparsely, such as when working with large datasets.

Conclusion

In this article, we studied about the Special Arrays in JavaScript. We got to know why we use them, along with the types of special arrays. We also studied about the advanced array methods with examples. You can refer to Arrays in Js to understand arrays better.

To learn more about Python, Import, and Modules in Python, you can visit Coding Ninjas Studio by Coding Ninjas. Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available; take a look at the interview experiences and interview bundle for placement preparations.

Happy learning, Ninja!

Previous article
JavaScript addEventListener() with Examples
Next article
JavaScript Document.write()
Live masterclass