JavaScript Array and Array Methods

JavaScript Array and Array Methods

Abstract:

Arrays in javascript is an object which is used to store multiple values having the same or different data types in a group. That means we can store elements of type Number, Boolean, String, Object, etc.

Arrays are represented by a pair of square brackets []. The values in an array are known as elements and their position is defined by index ( or indices). Each element in an array is separated by commas (,).

Scope of the article:

  • This article defines Array and ways to access the elements of an array. We also learn different methods of an array.
  • The article does not compare the array with other data types.

Contents:

  1. Definition
  2. Creation of an Array
  3. Accessing Elements
  4. Checking if the Given Value is an Array
  5. Adding an Element in an Array
  6. Deleting elements from an Array
  7. Determining Array Length
  8. Some Methods of Array
  9. Summary

Definition:

An array is a javascript object which is defined as a collection of elements of any type or simply a collection of data items stored under a single name. Array follows index-based access. The index is nothing but the position of the elements of an array. The index always starts with 0. The array comes under the category of composite or complex data types.

Here is an example of an array with five elements with types String, Boolean, Object, Array, and Number.

let myArray= ['Simran', true, {name: 'Simran', rating: 4.9}, ['html', 'css', 'javaScript' ], 156]

In the above example, Simran is at index 0, true is at index 1, and so on...

The total number of elements in an array gives the length of the array. In the above example, the length of myArray is 5. but this length is not fixed. We can change the length of an array anytime.

How to Create an Array:

  1. The most basic way to create an array is to simply assign the array values to a variable.

    const groceryList= [ 'egg', 'butter', 'bread', 'cereals', 'rice' ];
    
  2. Another way is to use the array constructor.

    • new Array(2): This will create an array of 2 elements but none of the elements will be defined.
    • new Array( 'egg', 'butter', 'bread' ): This will create an array of 3 elements with index 0 as egg, 1 as butter and 2 as bread.
      const groceryList= new Array('egg', 'butter', 'bread', 'cereals', 'rice');
      `
      
  3. Using Array.of() method: This method creates an array that has the argument as the value of its elements irrespective of the data type of that argument. Now you might think what's the difference between the Array constructor and the Array.of() method? The main difference between them is how they handle the integer arguments. Let us understand this by an example

    Array.of(4);     // [4]
    Array(4);     // array with 4 elements of value undefined
    

    So, the Array.of() method considers the argument as its element and not its length so it will make an array of length 1 with a value of 4 (argument), whereas if we pass 4 as an argument to the Array constructor then it will make an array of length 4 and all the 4 elements will be undefined.

    Array.of(2, 4, 6, 8);     // [2, 4, 6, 8]
    Array(2, 4, 6, 8);        // [2, 4, 6, 8]
    

    Let’s confirm this using the length property of the array

    console.log(Array.of(5).length);    //1
    console.log(Array(5).length);        //5
    

    So, this proves that the Array.of() method creates an array of 1 element while the Array constructor creates an array of 5 elements.

  4. Using Array.from() method: This is a static method used to create an array from any object with a length property or any iterable object.

    Array.of('Simran', true, {name: 'Simran', rating: 4.9}, 156)     // ['Simran', true, {website: 'Simran', rating: 4.9}, 156]
    console.log(Array.from('simran'));        // ['s', 'i', 'm', 'r', 'a', 'n']
    

How to Access the Elements of an Array:

We can access the elements of an array using its index.

const groceryList= [ 'egg', 'butter', 'bread', 'cereals', 'rice' ];
groceryList[0];        //egg
groceryList[1];        //butter
groceryList[2];        //bread
groceryList[3];        //cereals
groceryList[4];        //rice

If we want to access the elements of an array from backward, we can simply use the length property.

const groceryList= [ 'egg', 'butter', 'bread', 'cereals', 'rice' ];
const myLength= groceryList.length
groceryList[myLength-1];    //rice
groceryList[myLength-2];    //cereals
groceryList[myLength-3];    //bread

If we want to access all the elements of an array one by one then we can simply use a loop to save our time.

const groceryList= [ 'egg', 'butter', 'bread', 'cereals', 'rice' ];
for(var i=0; i<groceryList.length; i++){
    console.log(`Index=${i} Element=${groceryList[i]}`)
}

Output:

egg
butter
bread
cereals
rice

How to Check if the Given Value is an Array:

To check whether the given value is an array or not we use Array.isArray(value) method. This method returns true if the given value is an array.

Array.isArray('simran');   // false
Array.isArray(['simran', 146, 52]);  // true
Array.isArray(undefined);  // false
Array.isArray({totalMarks: 93}); // false

Adding an Element in an Array

The push() method is used to add an element at the end of an array and returns the new length of the array.

const groceryList= [ 'egg', 'butter', 'bread'];
var newLength=groceryList.push('cereals');
console.log(newLength);    //4
console.log(groceryList);    //[ 'egg', 'butter', 'bread', 'cereals']

You can also push more than one item at the same time.

groceryList.push('rice', 'juice', 'oil');

The push() method adds an element at the end of the array, but what if you want to add an element at the starting of the array? So here comes the unshift() method. The unshift() method is used to add an element at the starting of the array and returns the new length of the array. Like the push() method you can also add multiple values in the array using the unshift() method.

const groceryList= [ 'egg', 'butter', 'bread'];
var newLength=groceryList.push('cereals', 'rice');
console.log(newLength);    //5
console.log(groceryList);    //[ 'cereals', 'rice','egg', 'butter', 'bread']

Deleting Elements from an Array

The pop() method is used to delete the last element of an array and returns the deleted element.

const groceryList= [ 'egg', 'butter', 'bread', 'cereals', 'rice' ];
groceryList.pop();     // rice
console.log(groceryList);     // [ 'egg', 'butter', 'bread', 'cereals']

The shift() method is used to delete the first element of an array and returns the deleted element.

const groceryList= [ 'egg', 'butter', 'bread', 'cereals', 'rice' ];
groceryList.shift(); // egg
console.log(groceryList);     // [ 'butter', 'bread', 'cereals', 'rice']

Determining the Length of an Array

The length method is used to determine the length of an array.

const groceryList= [ 'egg', 'butter', 'bread', 'cereals', 'rice' ];
console.log(groceryList.length);    //5

Some Important Methods of Array in JavaScript

  1. slice(): This method is used to extract a specific portion of an array. It returns a new array and does not change the original array. Here start & end denotes the index of elements of the array. Syntax:
    slice() 
    slice(start)
    slice(start, end)  // end is not included
    
    Examples:
    const groceryList= [ 'egg', 'butter', 'bread', 'cereals', 'rice' ];
    console.log(groceryList.slice(2));        // ['bread', 'cereals', 'rice']
    console.log(groceryList.slice(2, 4));        // [ 'bread', 'cereals']
    console.log(groceryList.slice(1, 5));        // ['butter', 'bread', 'cereals', 'rice']
    console.log(groceryList.slice(-2));        // ['cereals', 'rice']
    console.log(groceryList.slice(2, -1));        // ['bread', 'cereals']     //extracting the third element through the second-to-last element in the sequence.
    
  2. concat(): This method is used to merge two or more arrays. This method does not change the original arrays but returns the new merged array. Example:
    const arrOne = [5, 10, 15];
    const arrTwo = [20, 25, 30];
    const arrThree=[35, 40, 45]
    const arrFour = arrOne.concat(arrTwo);
    const arrFive = arrOne.concat(arrTwo, arrThree)
    console.log(arrFour);        // [5, 10, 15, 20, 25, 30]
    console.log(arrFive);      // [5, 10, 15, 20, 25, 30, 35, 40, 45]
    
  3. join(): This method joins all the elements of an array and returns a new string separated by a separator. By default, the separator is a comma (,) but we can it by passing an argument to the join() method. Example:
    const groceryList= [ 'Egg', 'Butter', 'Bread', 'Cereals' ];
    console.log(groceryList.join());        // "Egg,Butter,Bread,Cereals"
    console.log(groceryList.join(''));        // "EggButterBreadCereals"
    console.log(groceryList.join('-'));        //"Egg-Butter-Bread-Cereals"
    
  4. fill(): This method fills all the array (or only the specified) elements with a static value. This method modifies the original array. Example:
    const groceryList= [ 'Egg', 'Butter', 'Bread', 'Cereals' ];
    groceryList.fill('Rice');
    console.log(groceryList);     // [ 'Rice', 'Rice', 'Rice', 'Rice' ]
    
  5. includes(): This method is used to check whether an element is present in an array or not. If the element is present then it will return true else it returns false. Example:
    const groceryList= [ 'Egg', 'Butter', 'Bread', 'Cereals' ];
    groceryList.includes('Rice')    //false
    groceryList.includes('Bread')     //true
    
  6. indexOf(): This method is used to find the index of an element in an array. If an element is not present then indexOf() method returns -1 Example:
    const groceryList= [ 'Egg', 'Butter', 'Bread', 'Cereals', 'Bread' ];
    groceryList.indexOf('Butter');     // returns 1
    groceryList.indexOf('Rice');     // returns -1
    groceryList.indexOf('Bread');     // returns 2
    
    If an element is present more than one time then the indexOf() method returns the index of its first occurrence. If we want to know the last occurrence of that element then use lastIndexOf().
    const groceryList= [ 'Egg', 'Butter', 'Bread', 'Cereals', 'Bread' ];
    groceryList.lastIndexOf('Bread');    // returns 4
    
  7. reverse(): This method reverses the position of all the elements in an array. This method modifies the original array. Example:
    const groceryList= [ 'Egg', 'Butter', 'Bread', 'Cereals' ];
    groceryList.reverse();         // returns [ 'Cereals', 'Bread', 'Butter', 'Egg']
    
  8. sort(): This method first converts all the elements of the array into a string and then sorts them in ascending order. This method modifies the original array. Example:
    const groceryList= [ 'egg', 'butter', 'bread', 'cereals', 'rice' ];
    groceryList.sort();    //returns [ 'Bread', 'Butter', 'Cereals', 'Egg', 'Rice' ]
    
  9. at(): As we have seen above, to access the elements of an array backward we use the length of an array. at() method allows us to directly traverse the array backward without using the length method by directly using negative value. Example:
    const groceryList= [ 'Egg', 'Butter', 'Bread' ];
    groceryList.at(0);     // Egg
    groceryList.at(1);     // Butter
    groceryList.at(2);     // Bread
    groceryList.at(-1);     // Bread
    groceryList.at(-2);     // Butter
    groceryList.at(-3);     // Egg
    

Summary

  • An array is a collection of data items (same or different) stored under a single name.
  • Array follows index-based access. The index always starts with 0.
  • For insertion of element we use push() & unshift() method whereas for deletion we use pop() & shift() method.
  • Some methods to create an array is using Array constructor, Array.of(), Array.from(), and the spread operator( ... )
  • Array.isArray(value) is used to determine if the passed value is an array or not.