Array Methods in JavaScript.

Array Methods in JavaScript.

In this article I have discussed about Array methods in JavaScript.

Hey people, I welcome you all to another write-up of mine. Hope you are doing well 😊 and yeah I'm doing good as well 🥰. So let's hop into the article 🧑‍🚀.

Arrays

  • Before starting with array methods let's understand what is an array

  • An array is a variable that holds more than one value. The syntax to declare an array in JavaScript is shown below

    let arrayName = [value1, value2, value2,....];
    
  • These values inside the array can be of different types i.e the value can be a number, string or boolean. Arrays in Javascript are slightly different from arrays in C and C++.

  • Let's see how to print an array with a code snippet.

In the above code snippet, I have declared an array name 'markClass' and given values to the array. For printing the array in the console I have written ' console.log(markClass);. The output in the terminal is shown below.

  • This is how we can declare an array and print it. Let's see how we can access a particular value from the array.

  • Each value in the array has an index attached to it. The first value in the array is given an index of 0, and the second value is given an index of 1 likewise the third value is given an index of 2 and so on. Let's understand this with an image attached below

  • Now to access any value inside an array we can simply write arrayname[index];

  • let's see a code snippet to be more clear on this thing😊.

let markClass = [67, 68, 78, 98, 97];
console.log("The array is :")
console.log(markClass);
console.log("The value 2 inside the array is :");
console.log(markClass[1]);//This is how to access a value inside an array
  • The output of the above code is attached below

  • I hope, you got a basic understanding of an array in JavaScript. So let's hop into the methods of an array in JavaScript 🧑🏻‍🚀.

Array methods in JavaScript

  • Array methods are built-in functions in JavaScript that we apply to an array. Each method performs a different operation on our arrays. Let's discuss each method one by one.

1. length

  • length:- This is not an array method but a property. It determines the size of an array. Let's be more clear on it with an example. In the below-given code snippet, the last line will give us the length of the array.
let markClass = [67, 68, 78, 98, 97];
console.log("The array is :")
console.log(markClass);
console.log("The value 2 inside the array is :");
console.log(markClass[1]);
console.log("The length of the array is ",markClass.length); //This will give us the length of the array.
  • The output is attached in the below image. Have a look at it.

2. push()

  • push():- This method will add one or more elements at the end of the array. Let's go into the coding mode 🤓.
let markClass = [67, 68, 78, 98, 97];
console.log("The array is :")
console.log(markClass);
console.log("The value 2 inside the array is :");
console.log(markClass[1]);
console.log("The length of the array is ",markClass.length);
let markClass1 = markClass;
markClass1.push("Hey🤓"); //This will add new element "Hey🤓" at the end
console.log("The new element will get added at the end of the array markClass1");
console.log(markClass1);
  • The output of the above code is attached below. Have a look at it.

3. pop()

  • pop():- This method will remove an element from the end of the array. Let's be more clear on it with an example ✨.
let markClass = [67, 68, 78, 98, 97];
console.log("The array is :")
console.log(markClass);
console.log("The value 2 inside the array is :");
console.log(markClass[1]);
console.log("The length of the array is ",markClass.length);
let markClass1 = markClass;
markClass1.push("Hey🤓");
console.log("The new element will get added at the end of the array markClass1");
console.log(markClass1);
markClass1.pop();
console.log("The last element will be removed from the array🚀.");
console.log(markClass1);
  • The output of the above code is attached below. Have a look at it.

4. unshift()

  • unshift():- This method inserts an element at the beginning of the array. Let's understand this with a code snippet.
let markClass = [67, 68, 78, 98, 97];
console.log("The array is :")
console.log(markClass);
console.log("The value 2 inside the array is :");
console.log(markClass[1]);
console.log("The length of the array is ",markClass.length);
let markClass1 = markClass;
markClass1.unshift("Hey🤓");// This will add the element "Hey🤓" at the beginning of the array.
console.log("The new element will get added at the beginning of the array markClass1");
console.log(markClass1);
  • The output of the above code is attached below. Have a look at it.

5. shift()

  • shift():- This method is used to remove an element from the beginning of the array. Let's understand this with a code snippet.

    let markClass = [67, 68, 78, 98, 97];
    console.log("The array is :")
    console.log(markClass);
    console.log("The value 2 inside the array is :");
    console.log(markClass[1]);
    console.log("The length of the array is ",markClass.length);
    let markClass1 = markClass;
    markClass1.unshift("Hey🤓");
    console.log("The new element will get added at the beginning of the array markClass1");
    console.log(markClass1);
    markClass1.shift(); //This will remove the first element from the array
    console.log("The first element will be removed from the array🚀..!!.");
    console.log(markClass1);
    
  • The output of the above code is attached below. Have a look at it.

6. slice()

  • slice():- This method copies a certain portion of the array, based on the start and end point we give to this method and returns the copied portion. The start and end points represent the index of the array. The endpoint is not included in the copied portion. This method will not affect the original array. The syntax of this method can be written as:-

    slice(start, end);
    slice(); // Here the start and end will be same as first and last index of the array respectively.
    slice(start); // here the end index will be the index of the last element in the array
    
  • Let's understand with a code snippet

    let markClass = [67, 68, 78, 98, 97,45,78,67,65];
    console.log('The original array is');
    console.log(markClass);
    let markClass1 = markClass.slice(3,6); 
    console.log("The portion of the markClass starting from index 3 and ending at index 5 will get displayed as output");
    console.log(markClass1);
    let markClass2 = markClass.slice(4);
    console.log("The portion of the markClass starting from index 4 till the end index will get printed");
    console.log(markClass2);
    
  • The output of the above code snippet is:-

7. splice()

  • splice() :- This method adds, replaces or removes elements from the array. This method changes the content of the array. Let's get more understanding of this method with a code snippet.

    let markClass = [67, 68, 78, 98, 97,45,78,67,65];
    console.log('The original array is');
    console.log(markClass);
    // Here 3 elements will be removed starting form the index 2 and at index 2 "NewElement" will be added.
    // I hope you got the significance of 2,3 and NewElement.
    // 2 represents the index from which the elements are to be deleted and replaced.
    // 3 represents how many elements to be deleted.
    // "NewElement" is the element to be added at index 2.
    let removedEle = markClass.splice(2,3,'NewElement');
    console.log("The removed elements are");
    console.log(removedEle);
    console.log("The original array is now")
    console.log(markClass);
    
  • The output of the above code is attached below. Have a look at it.

8. concat()

  • concat():- This method is used to merge two or more arrays. It doesn't change the existing array but returns a new array.

    let array1 = [1,2,3];
    let array2 = [4,5,6];
    let array3 = array1.concat(array2);
    console.log("The array3 will be")
    console.log(array3);
    
  • The result of the above code snippet will:-

9. fill()

  • fill():- This method fills the array with a fixed value from a start index(default 0) till the end index(default array.length). It modifies the array.

    let markClass = [61,72,33,64,75,87,99];
    console.log("The original array is");
    console.log(markClass);
    // Let's fill the array with static value 66 starting from index 2 to index 5
    console.log("The new array will be");
    console.log(markClass.fill(66,2,5));
    //Let's fill the array with static value 55 starting from index 2 till the length of the array.
    console.log("The new array will be");
    console.log(markClass.fill(55,2));
    
  • The result of the above code snippet is shown below:-

10. includes()

  • includes():- This method shows whether an array contains a certain value among its entries. If it contains then it will return true or else it will return false.

    let markClass = [61,72,33,64,75,87,99];
    console.log("The array is");
    console.log(markClass);
    console.log("Let's check whether the array contains 33 or not");
    console.log(markClass.includes(33));
    console.log("Let's check whether the array contains 23 or not");
    console.log(markClass.includes(23));
    
  • The output of the above code snippet is

11. indexOf()

  • indexOf():- This method will return the first index at which the given element can be found and if the given element is not found it will return 0.

    let markClass = [61,72,33,64,75,87,99];
    console.log("The array is ");
    console.log(markClass);
    console.log("The index of 33 is" +" "+markClass.indexOf(33));
    
  • The output of the above code snippet is:

12. isArray()

  • isArray():- This method checks whether the value passed is an array or not. If it is an array then it will return true or else it will return false

let markClass = [61,72,33,64,75,87,99];
let markClass1 = 34;
console.log("The array is ");
console.log("I will return true if the markClass is an ARRAY.");
console.log(Array.isArray(markClass));
console.log("I will return true if the markClass2 is an ARRAY.");
console.log(Array.isArray(markClass1));
  • The output of the above code snippet is

13. join()

  • The join() method returns a string by concatenating all the elements in the array, the elements of the new string are separated by a comma or a specified separator.
let markClass = ["I","am","a","programmer"];
console.log("The original array is");
console.log(markClass);
let newString1 = markClass.join(); //join without a specified separator. Default separator is comma :)
let newString2 = markClass.join('-'); //join with a specified separator.
console.log("The new string is");
console.log(newString1);
console.log("The new string with a specified separator is");
console.log(newString2);
  • The result of the above code snippet is given below.

14. toString()

  • The toString() method returns a string that consists of the elements of the array separated by a comma.
let markClass = ["Hey😀","people","I","love","you","all🤍"];
console.log("The original array is");
console.log(markClass);
let newString1 = markClass.toString(); //returns as string of array elements
console.log("The new string is");
console.log(newString1);
  • The output of the above code snippet is given below:-

15. sort()

  • This method converts the elements types into the string and then sorts them in alphabetical order(ascending order). The default sorting order is ascending. This method changes the original array.
let teamWc = ["Argentina","India","France","Portugal","Croatia","Netherlands"];
console.log("The unsorted array is");
console.log(teamWc);
console.log("The sorted array is");
console.log(teamWc.sort());

  • Let's try to sort an array with just number data type

    let teamWcRatings = [9,345,4534,3335,67,45];
    console.log("The unsorted array is");
    console.log(teamWcRatings);
    console.log("The sorted array is");
    console.log(teamWcRatings.sort());
    

  • You can see that the above result is not something that we expected. It is because all the elements are first converted to strings and then comparison is made between the element based on UTF-16 code unit values and then the values are sorted.

  • But if you want to sort them as per our expectations then javaScript provides a compare function.

  • sort() takes an optional compare function. If this function is provided as the first argument then the sort() method will consider these values(the values returned by the compare function) as the basis for sorting.

    let compare = (a,b)=>{
        return a-b;
    }
    let teamWcRatings = [9,345,4534,3335,67,45];
    console.log("The unsorted array is");
    console.log(teamWcRatings);
    console.log("The sorted array is");
    console.log(teamWcRatings.sort(compare));
    

  • if you want them in descending order then just replace return a-b; with

    return b-a; in the above code snippet.

16. reverse()

  • The reverse() method reverses the array such that the first element becomes the last element and the last element becomes the first element.

    let teamWcRatings = [9,345,4534,3335,67,45];
    console.log("The unsorted array is");
    console.log(teamWcRatings);
    console.log("The reversed array is");
    console.log(teamWcRatings.reverse());
    

17. map()

  • The map() method creates a new array by calling the provided function for every element of the original array. This method returns a new array.

    function addElement(num){
     let result = num + 10;
     return result;
    }
    let teamWcRatings = [12,13,21,42,23,11];
    console.log("The array is");
    console.log(teamWcRatings);
    let newArray1 = teamWcRatings.map(addElement);
    console.log("The new array after adding 10 to every element of teamEcRatings is");
    console.log(newArray1);
    

18. lastIndexOf()

  • The lastIndexOf() method returns the last index at which the given element can be found in the array or, -1 if it is not present.
let teamWc = ['Argentina', 'Brazil', 'Japan', 'India','Brazil'];
console.log("The array is");
console.log(teamWc);
console.log("The last index of Brazil is");
console.log(teamWc.lastIndexOf('Brazil'));

Conclusion🤍

  • So, here we come to the end of this particular article. These are few array methods we use commonly. There are a few more methods apart from the methods I have discussed in this article. I will discuss them in my future articles. So stay tuned 💫✨⭐️.

  • And one more thing 😁 comments and criticism are welcome.

Did you find this article valuable?

Support Pritam Chauhan by becoming a sponsor. Any amount is appreciated!