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.
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.
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);
You can also try this code with Online Javascript Compiler
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));
You can also try this code with Online Javascript Compiler
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.
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);
You can also try this code with Online Javascript Compiler
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]);
You can also try this code with Online Javascript Compiler
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);
});
You can also try this code with Online Javascript Compiler
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.