Arrays & its Methods in JavaScript

ยท

12 min read

Arrays & its Methods in JavaScript

An array is a data structure that allows us to store and manage multiple values in a single variable. They are essential in web development, and understanding arrays and their methods is crucial for any programmer. To get the most out of this article, it is advisable to have a basic knowledge of JavaScript. Here you can find my previous articles which will help you to prepare for the topic of this article :

In this article, we will explore various methods that can be used to manipulate arrays and make them work for us. We will be looking at some common methods such as push, pop, shift, unshift, sort, reverse, concat, slice, toString, join & fill. With these methods, we can add, remove, sort, manipulate, and fill arrays with values. By the end of this article, you will have a better understanding of arrays and their methods in JavaScript.

Definition:

It is a non-primitives datatype or value which can hold more than one value. It's an object (To know more about Objects) which has a method or properties. JavaScript arrays can contain different types of data types.

You can know more about Non-primitive datatypes in one of my articles, where I have explained everything about it in detail.

Why do we use Arrays?

Suppose you want to list the number of products. Storing every product to individual variables could take so much time and space. As shown below:

let product1= "bike";
let product2= "car";
let product3= "truck";
...
...
...

But what if you don't have this much time to store values individually, If you have hundreds of products, then you are left with only one solution, which is Array.

An array not only can hold many values under a single name, but also you can refer to any values by their index numbers (which start from zero). The first element of an array is at index 0 (zero), the second is at index 1, and so on.

Syntax:

let array-name = [item1, item2, ...];

Example:

let products= ["bike","car","truck"]

Array Methods

The length Property

the length property is used to know the number of array elements present in a particular Array. In JavaScript, the length of an array is equal to the highest array index plus one. If the highest array index is 3, then the length of the array is 4.

For example:

const ABCD = ["aaa", "bbb", "ccc", "ddd"];
console.log(ABCD.length);

Output:

The First Array Element

To access the first element of an array.

For example:

let ABCD= ["aaa", "bbb", "ccc", "ddd"];
console.log(ABCD[0]);

Output:

The Last Array Element

To access the last element of an array.

For example:

let ABCD= ["aaa", "bbb", "ccc", "ddd"];
console.log(ABCD[ABCD.length-1]);

Output:

The concat() method:

Example 1: Merging Two Arrays.

let num1 = [1, 2, 3, 4];
let num2 = [4, 5, 6, 7];
console.log(num1.concat(num2));

We defined 2 arrays num1 with elements [1, 2, 3, 4] and num2 with elements [4, 5, 6, 7]. We then called the concat method on num1 and passed num2 as an argument. The result of concatenating these two arrays was logged to the console using console.log().

The output would be in the browser's console:

Example 2: Merging multiple Arrays.

let num1 = [1, 2, 3, 4];
let num2 = [4, 5, 6, 7];
let num3 = [8, 1, 9, 0];
console.log(num1.concat(num2,num3));

We defined 3 arrays num1 with elements [1, 2, 3, 4], num2 with elements [4, 5, 6, 7], and num3 with elements [8, 1, 9, 0]. We then used the concat method to combine all three arrays and logged the result to the console using console.log().

The output would be in the browser's console:

The reverse() method:

It will reverse the array.

let ABCD=["aaa", "bbb", "ccc", "ddd"];
console.log(ABCD.reverse());

We defined an array ABCD with 4 elements "aaa", "bbb", "ccc", and "ddd". Then we called the reverse() method on the array and logged to the console using console.log().

The output would be in the browser's console:

The map() method:

Whatever is defined under the map() will apply to all elements of the Array.

For example:

let number = [4, 25, 64];
console.log(number.map(Math.sqrt));

We defined an array number with 3 elements 4, 25, and 64. Then we called the map() method on the array with Math.sqrt function and logged the result to the console using console.log().

The output would be in the browser's console:

The includes() method:

This method will check whether the array contains a specified value or not. It will return true if an array contains that specified value or it will return false.

For example:

let number= [ 1, 2, 3, 4, 5, "abc", 6, 7, 8, 9];
console.log(number.includes("abc", 5));

We defined an array number with elements [1, 2, 3, 4, 5, "abc", 6, 7, 8, 9]. Then we called the includes() method on the array with the argument "abc" and optional argument 5. The result of the includes() method, indicating whether the "abc" is found in the array starting from the index 5, is logged to the console using console.log().

The output would be in the browser's console:

The isArray() method:

It will check whether the object is an array or not. If an object is an array, it will return true otherwise, it will return false.

For example:

let one = [ 1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(Array.isArray(one));

let two = 11;
console.log(Array.isArray(two));

We defined two variables: one which holds an array of 9 elements, and two which holds the number 11. Then, we used Array.isArray() method to check if one and two are arrays. The result of the check for one & two logged to the console using console.log().

The output would be in the browser's console:

The positions of value

The indexOf() method:

It is used to check the position (index number) of the first occurrence of a value in an array and if the value is not found, it will return -1.

For example:

let number = [1, 2, 3, 4, 3, 5, 9, 3, 7];
console.log(number.indexOf(3));

We defined an array number with elements [1, 2, 3, 4, 3, 5, 9, 3, 7]. Then, we called indexOf(3) on the array and logged the result to the console using console.log().

The output would be in the browser's console:

The lastIndexOf() method:

This will check the position (index number) of the last occurrence of a value in an array and if the value is not found, it will return -1.

For example:

let number = [1, 2, 3, 4, 3, 5, 9, 3, 7];
console.log(number.lastIndexOf(3));

We defined an array number with elements [1, 2, 3, 4, 3, 5, 9, 3, 7]. Then, we called lastIndexOf(3) on the array and logged the result to the console using console.log().
The output would be in the browser's console:

Pushing & Popping

The push() method:

To insert elements in Array. We can add a new value to the Array using the push() method:

For example:

let ABCD= ["aaa", "bbb", "ccc", "ddd"];
ABCD.push("eee"); 
console.log(ABCD);

We defined an array ABCD with 4 elements "aaa", "bbb", "ccc", "ddd". Then we called push("eee") on the array to add the element "eee" to the end of the array. The updated array is then logged to the console using console.log().

The output would be in the browser's console:

Note: It will add the new elements at end of array after old element of that array.

The pop() method:

To pop out the last element of the array.

For example:

let ABCD = ["aaa", "bbb", "ccc", "ddd"];
ABCD.pop();
console.log(ABCD);

We defined an array ABCD with 4 elements "aaa", "bbb", "ccc", "ddd". Then we called pop() on the array to remove the last element from the array. The updated array ABCD is then logged to the console using console.log().

The output would be in the browser's console:

Shifting Elements

The shift() method:

It's similar to the pop(), but works on the first element instead of the last.

For example:

let ABCD= ["aaa", "bbb", "ccc", "ddd"];
ABCD.shift();
console.log(ABCD);

We defined an array ABCD with 4 elements "aaa", "bbb", "ccc", "ddd". Then we called shift() on the array to remove the first element from the array. The updated array ABCD is then logged to the console using console.log().

The output would be in the browser's console:

The unshift() method:

To insert a new element at the beginning of the array. It's the opposite to push().

For example:

let ABCD= ["aaa", "bbb", "ccc", "ddd"];
ABCD.unshift("eee", "fff"); 
console.log(ABCD);

We defined an array ABCD with 4 elements "aaa", "bbb", "ccc", "ddd". Then we called unshift("eee", "fff") on the array to add two new elements, "eee" & "fff", to the front of the array. The updated array ABCD is then logged to the console using console.log().

The output would be in the browser's console:

Slicing & Splicing Arrays

The slice() method:

It is used to slice some elements out of an array.

For example:

let ABCD= ["aaa", "bbb", "ccc", "ddd"];
console.log(ABCD.slice(0,2));

We defined an array ABCD with 4 elements "aaa", "bbb", "ccc", and "ddd". Then we called the slice() method on the array to extract elements from index 0 to index 2 (not inclusive) and logged the result to the console using console.log().

The output would be in the browser's console:

The splice() method:

It's used to insert new values into an array.

For example:

let ABCD= ["aaa", "bbb", "ccc", "ddd"];
ABCD.splice(2, 1, "eee", "fff");
console.log(ABCD);

In the above example, splice(2, 1, "eee", "fff"); The first parameter 2 indicates that the new elements will be inserted from an index 2 & the second parameter 1 indicates one element will be cut after a new element from the array. if we don't want to cut any elements, we can write 0 there. and if we want to cut more than 1 elements we can write as many as we want. And the next parameters "eee", "fff" are the new elements to be added.

The output would be in the browser's console:

Element "ccc" got eliminated because it's come after the new elements. If we have written 2 instead of 1 (like this splice(2, 2, "eee", "fff"); ), it would have been removed "ddd" too and the output would be ["aaa", "bbb", "eee", "fff"] .

Convert Array & String

The toString() method:

It converts an array to one single string element separated by commas. Apart from the Array object, all JavaScript objects have a toString() method.

For example:

let ABCD= ["aaa", "bbb", "ccc", "ddd"];
console.log(ABCD.toString());

We defined an array ABCD with 4 elements "aaa", "bbb", "ccc", & "ddd". Then we called the toString() method on the array and logged the result to the console using console.log().

The output would be in the browser's console:

There is another method to convert Array to String.

The join() method:

The join() method is similar toString() , converts an Array to a String without changing the original array. Separated by a comma (,) by default but you can specify anything to it.

For example:

let number= [1,2,3,4];
console.log(number.join('and'));

We defined an array number with 4 elements [1, 2, 3, 4]. Then we called the join() method on the number array with a separator 'and' and logged to the console using console.log().

The output would be in the browser's console:

The split() method:

This will split the string into an array of substrings. It will create a new array without changing the original string. ("") is used as a separator to split between words.

let name = "Yasir";
let array = name.split("");
console.log (array);

We defined a string name with a value "Yasir". Then we called split() method on the string with an argument "" that splits the string into an array of characters. Finally, we logged the result to the console using console.log().

The output would be in the browser's console:

Sorting Arrays

The sort() method:

This will sort the elements of the array in alphabetical order.

For example:

let animals= ["zebra", "lion", "tiger", "rabbit", "monkey"];
console.log(animals.sort());

We defined an array animals with 5 elements "zebra", "lion", "tiger", "rabbit", and "monkey". Then we called the sort() method on the array and logged the sorted array to the console using console.log().

The output would be in the browser's console:

The reverse(sort()) method:

We can also reverse the alphabetically arranged element by using The reverse() method: This will reverse the elements of the array in descending order.

For example:

let animals= ["zebra", "lion", "tiger", "rabbit", "monkey"];
console.log(animals.reverse(animals.sort()));

We have defined an array animals with 5 elements "zebra", "lion", "tiger", "rabbit", and "monkey". Then we called 2 methods on the array sort() & reverse(). The sort() method sorts the elements of an array in ascending order, so the final order of the elements in the animals array will be "lion", "monkey", "rabbit", "tiger", & "zebra". The reverse() method reverses the order of the elements in the array, so the final order of the elements will become "zebra", "tiger", "rabbit", "monkey", & "lion".

The output would be in the browser's console:

Array fill()

It is used to fill elements within an array. Refer to examples to understand it better.

For examples:

  1. Fill all the elements with a value:

     let array = [ 1, 2, 3, 4];
     array.fill("abc"); 
     console.log(array);
    

    We defined an array array with 4 elements [1, 2, 3, 4] Then we called fill() method on the array and passed it "abc" as an argument that is used to fill all elements of the array with the same value "abc". Finally, we logged the array to the console using console.log().

    The output would be in the browser's console:

  2. Only fill in the selected elements:

     let array = [ 1, 2, 3, 4];
     array.fill("abc", 2, 3);
     console.log(array);
    

    In this case, the start index and end index are specified ("abc", 2, 3) and the element (value 4) of end index 3 did not get changed. fill() method overwrites the original array.

Conclusion:

Arrays are a crucial data structure in programming. They allow us to store & manipulate collections of data efficiently. JavaScript provides several array methods that make it easy to perform various operations on arrays. So far I've almost covered all important Methods of Array of Javascript. Understanding these methods is essential for any JavaScript developer as they are widely used in various applications. With these tools, we can efficiently store and manipulate arrays, making our code more concise and easier to maintain.

Thank you for reading. Feel free to comment on this, if found it useful.

Happy learning.๐Ÿ˜‡๐Ÿ˜‡๐Ÿ˜‡

ย