Array (data structure)

Array (data structure)

Table of contents

No heading

No headings in the article.

What is an Array ?

An array is an object where we can store more numbers of data in a single variable like a list. Each element in the array is accessed and we can add a new element or can remove the element. Whereas in a single variable we can add a single element (value), and for more number of values have to create separate variables which is time-consuming and much slower. The array on another side makes the work much easier and less time-consuming.

  • The element inside an array can be accessed using integers as indexes, which always starts from 0,1,2....n-1 i.e the first element is always at index 0 the second element is on index 1 and so on. Whereas the last element can be accessed using length -1property.

There are three-way that an Array can be constructed -

  • By array literal-
            const friends=['mohan','mark','rohan','sohan'];
  • By creating an instance of Array directly (using a new keyword)-
  const arr=new Array();
               arr[0]='Jack';
               arr[1]='Mack';
               arr[2]='Ram';

              console.log(arr);
  • By using an Array constructor (using the new keyword) -
       const arr=new Array('Jack','Mack','Ram');

                  for(let i=0;i<arr.length;i++)
                 {
                  console.log(arr[i]);
                  }

/*In this example, I have used ***for loop*** to access
 each element individually.

 have used a length property in the for loop, I am going to 
explain it later in this blog.  */

Arrays are non-primitive, i.e elements inside an array can be mutated despite it being declared using const variables but the entire array cannot be replaced.

  • Example: If you try to replace an element from an array.
  const friends=['mohan','mark','rohan','sohan'];
   friends[0]='jack';
   console.log(friends);

    // output: ['jack', 'mark', 'rohan', 'sohan'];
  • Example: If you try to replace an entire array.
     const friends=['mohan','mark','rohan','sohan'];

     friends=['bod','ram']


    //This type of error will occur.
      error: Assignment to constant variable.

The array can hold mix number of data types. For example data types that an array can hold are - numbers, strings, boolean, functions, objects, and even other arrays(can put array inside an array) etc.

  • Example: Types of data an array can hold.
     const friends=['mohan',12,true,function(){},object{},arr[]];

Methods

Array methods are JavaScript functions that we may apply to our arrays – each method has its own function that performs a change or computation to our array, saving us from having to write common functions from start. There are more than 20 Array methods in JS, but here we will discuss a few of them.

Array. slice() - These methods give the shallow copy of elements from the original array, it does not mutate the original array. The syntax used is slice(start, end) where 'start' is a starting index of the array from where we want to start copying and 'end' is the last index of the array until where we want to copy. a different way to use the slice syntax is-

  • slice() - It returns a new array, with all the elements.
  • slice(start) -It returns a new array with all the elements starting from the start index and ignoring the one before that index.
  • slice(start, end) - It returns a new array containing all the elements starting from the start index up until the end-1 position.

(Note: It copies from start to end-1 position)

  • Example: Array. slice method.
     const friends=['mohan','mark','rohan','sohan','ram','sita'];
      // shallow copy
         console.log(friends.slice());
         // output:['mohan', 'mark', 'rohan', 'sohan', 'ram', 'sita'];


     // single parameter-->
        console.log(friends.slice(2));
        // output: ['rohan', 'sohan', 'ram', 'sita'];

    // two parameters

        console.log(friends.slice(2,5));
       // output: ['rohan', 'sohan', 'ram'];


   // if wanted to include last element.
        console.log(friends.slice(2,6));
        // output: ['rohan', 'sohan', 'ram', 'sita'];


       console.log(friends.slice(2,-1));
       // output:['rohan', 'sohan', 'ram'];

Read more about the Slice method here..

Array. splice() - This method does the same as the slice method i.e it also removes or replaces the element or adds a new element in an existing array but it mutates the original array. The syntax used in the splice method is splice(start, deleteCount, item) where 'start' is a starting index of the array from where the particular element is replaced or inserted whereas 'deleteCount' is just an integer that keeps track of a number of an element have to remove and here the 'item' indicates the element that is to be inserted to the array. Different ways to use the splice syntax are-

  • splice(start): It returns the array with a removed element from the 'start' index until the end-1 index.
  • splice(start, deleteCount, item): It returns the array with a replaced element from the 'start ' index and it is based on 'deleteCount' i.e how many elements are to be replaced from that start is based on deleteCount, and the element is to be replaced with the given 'item'.
  • Example : Array.splice() method.
    const friends=['mohan','mark','rohan','sohan','ram','sita'];


     friends.splice(1,0,'mack');
     // inserts at index 1.
     console.log(friends);
     /* output: ['mohan', 'mack', 'mark', 'rohan',
         'sohan', 'ram', 'sita']; */


     friends.splice(3,1,'jane');
    // replaces 1 element at index 3;
     console.log(friends);
    /* output: ['mohan', 'mack', 'mark', 'jane', 
        'sohan', 'ram', 'sita'];    */

Read more about the splice method here..

Array. pop() -This method removes the last element i.e pops out the last element of the array and returns the removed element. syntax use is pop().

  • Example : Array.pop() method.

     const friends=['mohan','mark','rohan','sohan','ram','sita'];


    console.log(friends.pop());
    // output: sita

Read more about the pop method here..

Array. push() - This method does the opposite of the pop method i.e it adds an element to the end of the array and returns the new length of the array.push().

  • Example : Array.push() method.
    const friends=['mohan','mark','rohan','sohan','ram','sita'];


    console.log(friends.push('sam'));
    // output: new length of the array 7.

Read more about the push method here..

Array. unshift() - This method adds elements at the beginning of an array and returns the new length of the array.

  • Example : Array.unshift() method-
     const friends=['mohan','mark','rohan','sohan','ram','sita'];


     console.log(friends.unshift('sam'));
    // output: new length of the array 7.
     console.log(friends);
    /*output: ['sam', 'mohan', 'mark', 'rohan', 
       'sohan', 'ram', 'sita']  */

Read more about the unshift method here..

Array. shift() - This method removes the first element from the array and returns the element, it also changes the length of the array.

  • Example : Array.shift() method -
     const friends=['mohan','mark','rohan','sohan','ram','sita'];


     const firstRemovedItem=friends.shift();
      console.log(friends);
     // output: ['mark', 'rohan', 'sohan', 'ram', 'sita']
      console.log(firstRemovedItem);
      // output: removed item: mohan

Read more about the shift method here..