Special arrays in JavaScript


In this problem statement, our task is to show working of some special arrays and their characteristics in Javascript programming. In Javascript a special array can be dependent on the given context. The special arrays can refer to different types of arrays depending on the condition and context. There are some interpretations possible: Typed arrays, Sparse arrays and Array with string keys.

What is the Typed Array?

In Javascript there are many built-in methods available for typed array objects. These arrays are special in the context that they represent the array of a specific type of data in it. These kinds of arrays have a fixed length and also allow manipulation of large amounts of binary data. The built-in methods for typed arrays are Int8Array, Int16Array, BigIntArray, and so on.

//typed array of 8-bit integers
const arr = new Int8Array(4);
// define values in the array with bracket notation
arr[0] = 11;
arr[1] = 12;
arr[2] = 13;
arr[3] = 14;

console.log(arr);
console.log(arr.length);

What is the Sparse Array?

In Javascript programming, We generally work with arrays having keys for every object. But we have another array known as sparse arrays, which is usable as objects with some numeric keys, but it is possible to create arrays with some missing keys.

// define an empty array for sparse array
const sprArr = [];
sprArr[0] = 'sparse1';
sprArr[1] = 'sparse2';
sprArr[3] = 'sparse3';
console.log(sprArr.length);
//print undefined element
console.log(sprArr[2]);
//print whole array
console.log(sprArr);

What is the Array with string keys?

In Javascript arrays are usually defined with numeric keys and when we access any object we access it with the respective keys. But we can also define non-integer keys with the help of Javascript functionalities. This can be useful in some contexts.

const obj = {
   'a': 'stringKey1',
   'b': 'stringKey2'
};
//array with string keys
const arrWithStringKey = [obj['a'], obj['b']];
console.log(arrWithStringKey);

Time Complexity

The time complexity for all the above codes are different in different inputs and outputs. Some code and lines are executed in O(n) time but some code is using O(1) time to complete the execution. As these implementations are very basic codes to understand the special arrays in Javascript and we can use them as per the application requirements.

Conclusion

As we have seen different types of special arrays in Javascript. We have learned about typed arrays, sparse arrays and arrays with string keys. These are the special arrays in terms of usage and different from the original and default arrays.

Updated on: 18-May-2023

277 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements