Array and its methods in JavaScript

Array and its methods in JavaScript

In programming, Array is a collection of elements or data. It is a widely used data structure in all programming languages. We express the Array in a square bracket[]and each element is separated by a comma.

How to create an Array?

We can create an array in many ways, and among them, the most common way is by declaring an array and assigning value to it like this:

const myArray = [1, true, "ABC", null, undefined]

But this is not the only way, we can also create an array by using the Array constructor. This method looks like this:

const myArray = new Array(1, true, "ABC", null, undefined)

We can have all kinds of datatype in a single array, and even we can have another array or object inside one array in JavaScript. To extract data from an element, we have to call the array name and then the index number of the required element in a square bracket (NOTE: The counting of Index number starts from 0, so to get the 3rd value from an array we need to set the index as 2). For example:

myArray[2] //'ABC'

Here we will discuss important methods of Array in JavaScript:

✨ push():

The push() method is used to insert an element at the end of an Array. Let's see this method by adding my name at the end of myArray:

myArray.push("Subham")
console.log(myArray)
//[ 1, true, 'ABC', null, undefined, 'Subham' ]

✨ unshift():

Just like push() method unshift() method also adds elements in Array but at the beginning of the array. Let's see an example:

myArray.unshift(0)
console.log(myArray)
//[ 0, 1, true, 'ABC', null, undefined, 'Subham' ]

✨ pop():

This method eliminates the last element from the array. Example:

myArray.pop() //'Subham'
console.log(myArray) //[ 0, 1, true, 'ABC', null, undefined ]

✨ shift():

This method also eliminates one element from the array, but unlike pop() it removes the first element from the array. Example:

myArray.shift()//0
console.log(myArray) //[ 1, true, 'ABC', null, undefined ]

✨ indexOf():

This method is used to find the index of a particular element in the array. Example:

myArray.indexOf(null) //3

✨ reverse():

This method is used to reverse the position of elements in an array. Example:

myArray.reverse() //[ undefined, null, 'ABC', true, 1 ]

✨ fill():

This method is used to fill all elements of an array with a particular element. Example:

myArray.fill(10) //[ 10, 10, 10, 10, 10 ]

✨ toString():

This method converts all elements of the array into a single string, separated from each other by a comma. Example:

const Arr = [5, 9, 7];
console.log(Arr.toString()) //'5,9,7'

✨ sort():

This method is used to sort elements of an array in ascending or descending order, but sortin JavaScript works a little differently from other languages. At first, it converts the elements of the array into strings and then sorts it according. So in the case of a normal string array, it returns the expected result as this example:

const arr1 = ["ab", "cd", "bc"];
arr1.sort() // ['ab', 'bc','cd']

but in the case of numbers, it becomes complicated like this:

const arr2 = [10, 8, 17, 300];
arr2.sort() //[ 10, 17, 300, 8 ]

In this situation, we can pass a comparison function to the sort method to get the expected result like this:

arr2.sort((a,b) => a-b) //[ 8, 10, 17, 300 ]

We can also sort the array in descending order by changing the function like this:

arr2.sort((a,b) => b-a) //[ 300, 17, 10, 8 ]

✨ map():

This method is used to execute a particular function in every element of an array. It returns a transformed array with the function applied to each element. Example:

arr3 = [2, 3, 4, 5, 6];
arr= arr3.map((x) => x+5);
console.log(arr) //[ 7, 8, 9, 10, 11 ]

✨ filter():

As the name suggests, this method filters a given array and returns a new array with only the element that complies with the condition given in the filter method. Let's see this with an example:

const arr4 = [3, 5, 9, 15, 35, 77];
const filteredArr = arr4.filter(x => x>20);
console.log(filteredArr) //[ 35, 77 ]

✨ concat():

This method is used to merge two different arrays into a single array. Example:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = arr1.concat(arr2);
console.log(arr3) //[1, 2, 3, 4, 5, 6]

✨ find() & findLast():

As we have seen in the filter method, these methods also return based on the condition given, but unlike filter these only returns the first (in the case of find()) and last (in the case of findLast()) element. We can also find the index of these elements by using findIndex() and findLastIndex() method. Let's see all these methods with some examples:

const array1 = [3, 8, 19, 25, 57, 36, 90];
const array2 = array1.find(x => x>50);
const array3 = array1.findLast(x => x>50);
console.log(`result of find = ${array2} and findLast = ${array3}`);
// result of find = 57 and findLast = 90
console.log(array1.findIndex(x => x>50)) //4
console.log(array1.findLastIndex(x => x>50)) //6

✨ reduce():

In this method, we have to supply a callback function in the reduce method and the method applies this function to each element and returns a single result from that. This example will help to understand the concept:

const arr = [1, 3, 5];
const reduced = arr.reduce((a,b) => b-a);
console.log(reduced) // 3

✨ slice():

This method returns a new array with user-specified start-to-end index elements from the given array. Example:

const arr = ["A", "B", "C", "D", "E", "F"];
console.log(arr.slice(2,5)) //[ 'C', 'D', 'E' ]

In this example, the first parameter in the slice method denotes the starting index and the last parameter is the end index of the array.

✨ splice():

By this method, we can add, remove or modify any element from any index of an array. Let's see an example:

const arr = ["A", "B", "C", "D", "E", "F"];
//Eg. 1:
arr.splice(2,2); 
console.log(arr); //[ 'A', 'B', 'E', 'F' ]
//Eg. 2:
arr.splice(2,0, "C", "D");
console.log(arr) //[ 'A', 'B', 'C', 'D', 'E', 'F' ]

So here the syntax is:

array.splice(starting index, number of element to remove, elements to add)

In the first example, we have only provided the first two parameters, so it did not add any new elements but removed two elements starting from index number 2. In the second example, we have mentioned what elements to add and in the second parameter we have provided 0 as a value, so it did not remove any element from the array but added new elements from index number 2.

🧩 Conclusion:

These are the most commonly used array methods. These methods make a manipulating arrays in JavaScript so easy for us, so we must have to learn them properly.

Thanks for reading. Please leave your feedback below.