Javascript Array Methods

Javascript Array Methods

In this article, you'll learn about JavaScript array methods with the help of examples.

ยท

7 min read

What is an Array?

In simple terms, an array is an object which is a non-primitive datatypes category, and it means that we can assign it a group of values at once. It is enclosed by square brackets. Let us understand the syntax and how we create it.

  • To create an empty array, you only need [] two square brackets. It is called an array literal.
//Empty array
const emptyarray = []
  • You can create an array using two ways:
  1. array literal: You can use array literals to create an array which is mostly used and recommended in practice. You'll find the empty array now filled with candies.
//Candies
const candies = ["guava", "mango", "orange", "tamarind"];
//We can store any type of values in an array.
const anyvalue = [1, "candies", "coding", true]
  1. new keyword:
//Candies
const candies = new Array("guava", "mango", "orange", "tamarind");

Gif description

Do you remember your childhood during your chocolate distribution in the school on your birthday, let's say you used to have a horizontal box with different candies in it. That box you can call an array and the candies in it as its elements. The length of an array will be the number of candies in the box and the index of an array will be the position/location of the candy from the initial position which would be zero. Check the below index of the candies from the array:

//Candies
const candies = ["guava", "mango", "orange", "tamarind"];

0- guava
1- mango
2- orange
3-tamarind

In this candy box, now we want to perform many operations which will be introduced with Javascript Array Methods.

Javascript Array Methods

Gif description

Access Elements of an Array

  • How do access an orange candy in the candies array by specifying the index number of their position in the array?

    //Candies
    const candies = ["guava", "mango", "orange", "tamarind"];
    //Accessing the element by index value.
    console.log(candies[2]); 
    //Output:
     Orange
    

Access the index of an element in an Array

  • The indexOf() method helps us to search for an element of an array and return its position. Let's say, we want to have a tamarind candy from the box, we will search for it.
//Candies
const candies = ["guava", "mango", "orange", "tamarind", "tamarind"];
//Accessing the index value of an element.
console.log(indexOf("tamarind"); 
//Output:
 3
////Accessing the last index value of an element.
console.log(lastIndexOf("tamarind");
//Output:
4

The output is not 4 but 3 since the method will pick the index of the element where it was found the first time. In case, instead of the first time, you want to access the index of the last time, then you can use lastIndexOf().

  • The includes() method will simply return true as an output if the array includes that element we are trying to search.
//Candies
const candies = ["guava", "mango", "orange", "tamarind"];
//Accessing the index value of an element.
console.log(candies.includes("tamarind")); 
//Output:
 True

Add an Element to an Array

  • The push() method will add a pineapple candy at the end of the candies box.

    //Before adding pineapple candy
    const candies = ["guava", "mango", "orange", "tamarind"];
    //Push method to add an element at the end
    candies.push("pineapple");
    //Output:
    ["guava", "mango", "orange", "tamarind", "pineapple"]
    
  • The unshift() method will add a blueberry candy at the start of the candies box.

    //Before adding blueberry candy
    const candies = ["guava", "mango", "orange", "tamarind"];
    //Unshift method to add an element at the start
    candies.unshift("blueberry");
    // Output:
    ["blueberry","guava", "mango", "orange", "tamarind"]
    

Two methods are used to add an element to an array. The first push method adds an element at the end of any array whereas unshift method adds an element at the start of an array.

Change the Elements of an Array

  • We will change the candy box by grape candy in the place of orange candy. How can we do that? By accessing the index value.
//Before changes made
const candies = ["guava", "mango", "orange", "tamarind"];
//Changing by accessing the index value
candies[2] = 'grape';
//Output:
["guava", "mango", "grape", "tamarind"]
  • We can also add grape candy without making any changes to the orange candy element. Let's see how we do this too.
//Before changes made
const candies = ["guava", "mango", "orange", "tamarind"];
//Without changing the orange candy element
candies[2] = 'grape';
//Output:
["guava", "mango", "orange", "tamarind", "orange"]

Remove an Element from an Array

  • The pop() method will remove the last element candy from the candies array and it changes the original array.
//Before removing
const candies = ["guava", "mango", "orange", "tamarind"];
//Applying the pop method
console.log(candies.pop())
//Output returns the removed element
tamarind
//Print candies array
console.log(candies)
//Candies array length reduced after applying the method
["guava", "mango", "orange"]
  • The shift() method will remove the first element candy from the candies array and it changes the original array.
//Before removing
const candies = ["guava", "mango", "orange", "tamarind"];
//Applying the shift method
console.log(candies.shift())
//Output returns the removed element
guava
//Print candies array
console.log(candies)
//Candies array length reduced  by 1 element after applying the method
["mango", "orange", "tamarind"]
  • The slice() method doesn't change the original array. Instead, it returns a new array containing a section of the original array on which the slice method is applied. The section is represented by a start and end index of the elements in the array. For instance, we want to select the section from mango to orange.
slice(start, end);
  • The starting index for mango will be 1 which defines from where we want to start the slicing and the ending index till orange will be 3. Instead of 2 index of the orange element, why do we use 3? You can just note that we will specify the index of the element where we just want to stop the slicing of a portion. So, it is 3.

  • Time to write and implement the code now.

//Before slicing
const candies = ["guava", "mango", "orange", "tamarind"];
//Applying the slice method
console.log(candies.slice(1, 3));
//Output returns the sliced portion
["mango", "orange"]
//Print candies array
console.log(candies);
//Output of original array will remain same.
["guava", "mango", "orange", "tamarind"]
//The new array with sliced method applied.
slicedarray = console.log(candies.slice(1, 3));
console.log(slicedarray);
//Output
['mango', 'orange']
  • The splice() method modifies the original array. It deleted the elements from an array and inserts the new elements in the same array. It has starting index, delete count and (element1, element2, ..., elementNth) to insert in an array.
//Before splicing
const candies = ["guava", "mango", "orange", "tamarind"];
//Applying the splice method
console.log(candies.splice(1, 2, "cranberry", "avacado"));
//Returns the spliced portion output
["mango", "orange"]
//Print candies array
console.log(candies);
//Output of the same array
["guava", "cranberry", "avacado", "tamarind"]

Other methods

  • The concat() method takes two or more arrays and concatenates them into one. It will not change the existing array.
// Array 1
const candies1 = ["guava", "mango"];
// Array 2
const candies2 = ["orange", "tamarind"];
// Applying Concatenation
console.log(candies1.concat(candies2));
// Output after concat() method
["guava", "mango", "orange", "tamarind"]
  • The fill() method modifies the original array. It fills the elements of an array with a static value from the start position to the end position. If the start or the end index positions are not specified, the whole array is filled.
// Candies
const candies = ["guava", "mango", "orange", "tamarind"];
// When no start and end index are specified
console.log(candies.fill("apple"));
// Output
["apple", "apple", "apple", "apple"]
// Candies1
const candies1 = ["guava", "mango", "orange", "tamarind"];
// When the start and the end index are specified
console.log(candies1.fill("apple", 2, 4));
// Output
["guava", "mango", "apple", "apple"]
  • The join() method returns a string by joining all the elements in an array.
// RIYA
const myname = ["R", "I", "Y", "A"];
// Joining the letter elements by giving space.
console.log(myname.join(" "));
// Output
R I Y A
// Joining the letter elements by giving arrow sign.
console.log(myname.join("->"));
// Output
R->I->Y->A
  • The isArray() method returns true if the object is an array and false if it is another datatype.
// Candies
const candies = ["guava", "mango", "orange", "tamarind"];
// isArray
output = Array.isArray(candies);
console.log(output)
// Output
true

// String
let myname = "Riya";
// isArray
output = Array.isArray(myname);
console.log(output);
// Output
false
  • The sort() method sorts the elements in alphabetic order.
// Candies
const candies = ["guava", "mango", "cranberry", "avacado"];
// Sorting
console.log(candies.sort())
// Output
["avacado", "cranberry", "guava", "mango"]
  • The reverse() method reverses the elements of an array.
// Candies
const myname = ["R", "I", "Y", "A"];
// Reverse
console.log(candies.reverse())
// Output
["A", "Y", "I", "R"]
  • The map() method doesn't change the existing array and It creates a new array by calling the provided function for each element of an array.
// Numberlist
const nums = [2, 3, 4, 5, 6];
// Numberlist element*10
const multiply = nums.map(element => element*10);
console.log(multiply);
// Output
[ 20, 30, 40, 50, 60 ]

So, this was all we have covered about the array and its methods. Thank you for reading this far, See you in the next article. Happy Coding! ๐Ÿค“

Time to have some candies!๐Ÿ˜

Gif description

ย