Arrays in JavaScript an in depth guide

Arrays in JavaScript an in depth guide

What are Arrays in JavaScript

Arrays are a neat way of storing data items under a single variable name. So that we can access those data items very easily later in the program and use them to perform useful operations.

Let's say if we don't have arrays then, in that case, we need to store each item in a separate variable and then we need to perform operations on them which becomes a very difficult and tedious task that's when arrays come in very handy.

CRUD(Create, Retrieve, Update, Delete) operations on Arrays

Creating Arrays

Arrays consist of square brackets and data items that are separated by commas

  • let's say we want to store shopping items for the weekend we can store them in a below way
const shop=["grocery", "hat", "pen" ,"book"];
console.log(shop)
  • In the above example, we only stored data items with only string data type but we can also store items of different types like - string, object, number, and array within an array
const squares=[1,4,9,16];
const random=[1,"hi",[2,3,4],{'fname':' xyz'}];

Retrieving(Accessing array items)

  1. Items in an array are numbered, starting from zero. This number is called the item's index. So the first index is starting from 0 and the second is 1 and so on. You can access individual items of the array using square brackets and passing the index value the same we access characters in a string type.
const shop=["grocery", "hat", "pen" ,"book"];
console.log(shop[0]);
// returns "grocery"
  1. When an array is embedded inside another array it is called a multidimensional array, in that case, we can access the inside array item by chaining the square brackets and passing index values, we could do something like the one below.
const shop=["grocery", "hat", "pen" ,"book",[1,4,5,6]];
console.log(shop[4][3]);
// returns 6 the last item in inside array
  1. We can also access the index number of an item in an array using indexOf() method
const sports=["cricket", "football","kabaddi"];
const indexOfKabaddi=sports.indexOf("kabaddi");
console.log(indexOfKabaddi);// 2

Updating an array

  1. Arrays in place modify by accessing items using an index and assigning the value.

     const shop=["grocery", "hat", "pen" ,"book"];
     shop[2]="pencil";
     console.log(shop);
     // returns ["grocery", "hat", "pencil" ,"book"]
    
  2. To add one or more items to the end of an array we can use push() method

const cities=["Bangalore", "Delhi", "Frankfurt", "New York"];
cities.push("Hyderabad");
console.log(cities); // ["Bangalore", "Delhi", "Frankfurt", "New York","Hyderabad"]
cities.push("pune","indore");
console.log(cities); // ["Bangalore", "Delhi", "Frankfurt", "New York","Hyderabad","pune","indore"]

The the the new length of an array is returned when the method call completes if you wanted to store a new array length we could do something like the below:

const cities=["Bangalore", "Delhi", "Frankfurt", "New York"];
const newLength=cities.push("Hyderabad");
console.log(cities);// ["Bangalore", "Delhi", "Frankfurt", "New York","Hyderabad"]
console.log(newLength);//5
  1. To add the items to the start of the array using unshift():
const cities=["London","Bangalore"];
cities.unshift("Goa");
console.log(cities);//["Goa","London","Bangalore"]

Deleting(Removing) items from the array

  1. Remove the last items from the array using the pop() method.

pop() doesn't take any parameters it just removes the last element

const rivers=["kaveri", "ganga", "krishna"];
rivers.pop();
console.log(rivers);//["kaveri", "ganga"];

the pop() method returns the removed item we can store that in a variable for our reference.

const rivers=["kaveri", "ganga", "krishna"];
const removedItem=rivers.pop();
console.log(rivers);//["kaveri", "ganga"];
console.log(removedItem);//Krishna
  • To remove the first item from the array use the shift() method.
const rivers=["Kaveri", "ganga", "Krishna"];
const removedItem=rivers.shift();
console.log(rivers);//["ganga", "Krishna"];
console.log(removedItem);//Kaveri
  • If you know the index of an item, you remove it from the array using splice() method.
const rivers=["kaveri", "ganga", "Krishna","Godvari","ghatprabha"];
const index=rivers.indexOf("ganga");
cities.splice(index,2);//["Krishna","Godvari","ghatprabha"]

Accesing every item

very often you may want to access every item in the array. You can do this using for..of

const birds=['Parrot', 'Owl', 'Falcon'];
for(const bird of birds){
     console.log(bird);
}

Converting between strings and arrays

const data = 'Manchester,London,Liverpool,Birmingham,Leeds,Carlisle';
const cities=data.split(',');
console.log(cities);//['Manchester','London','Liverpool','Birmingham','Leeds','Carlisle']
  • The above code splits each item by a comma

  • You can go another way around by using join() method

const cities = ['Manchester','London','Liverpool','Birmingham','Leeds','Carlisle'];
const commaSeparated=cities.join(',');
console.log(commaSeparated);//'Manchester,London,Liverpool,Birmingham,Leeds,Carlisle'
  • The above code snippet combines all the array items into one string wherein each item is separated by , as we gave .join(',')
const cities = ['Manchester','London','Liverpool','Birmingham','Leeds','Carlisle'];
const plusSeparated=cities.join('+');
console.log(plusSeparated);//Manchester+London+Liverpool+Birmingham+Leeds+Carlisle
  • You can combine array items using to_string method doesn't take any parameters
const cities = ['Manchester','London','Liverpool','Birmingham','Leeds','Carlisle'];
const commaSeparated=cities.toString();
console.log(commaSeparated);//'Manchester,London,Liverpool,Birmingham,Leeds,Carlisle'

Length of an Array

const birds=['parrot','Hen','Duck'];
const birdsLength=birds.length;
console.log(birdsLength);//3
console.log(birds['length']);//3

Array methods

The Array object has the following methods.

  • concat() joins two or more arrays and returns a new array

      let myArray=[1,2,3];
      myArray=myArray.concat('a','b','c');
      // myArray is now ["1", "2", "3", "a", "b", "c"]
    
  • join(delimiter=', ') method joins the array items into a string

      let arr1=[1,2,3,4,5];
      arr1=arr1.join(' - ');
      console.log(arr1);
      // logs 1 - 2 - 3 - 4 - 5
    
  • push() method adds one or more elements to the end of an array and returns length of the resulting array.

      const arr1=[1,2,3,4];
      const arr1Length=arr1.push(5);
      console.log(arr1,arr1Length);//[1,2,3,4,5] 5
    
  • the pop() method removes the last element from an array and returns that element.

      const arr1=[2,4,6,8,'egg'];
      const lastItem=arr1.pop();
      console.log(arr1,lastItem);//[2,4,6,8] egg
    
  • shift() method removes the first element from an array and returns that element.

      const arr1=[1,2,3,4,5];
      const first=arr1.shift();
      console.log(arr1,first);[2,3,4,5] 1
    
  • unshift() method adds one or more elements to the front of an array and returns the new length of the array

      const arr1=['one',2,true,3];
      const newLength=arr1.unshift(0,'hi');
      console.log(arr1,newLength);// prints [ 0, 'hi', 'one', 2, true, 3 ] 6
    
  • splice(start_index,up_to_index) method extracts a section of an array and returns a new array and the original array is going to be modified.

      const arr1=['a','b','c','d','e'];
      const arr2=arr1.splice(1,3);
      console.log(arr1,arr2);//['a','e'] ['b','c','d']
    
  • splice(start_index,count_to_remove,addElement1,addElement2,.......) method removes the elements from the array (optionally) and replaces them. It returns the items which were removed from the array.

      const myArray = ['1', '2', '3', '4', '5'];
      myArray.splice(1, 3, 'a', 'b', 'c', 'd');
      //[1,'a','b','c','d',5]
    
  • reverse() method transposes the elements of an array, in place: the first array element becomes last and the last, becomes first. It returns the reference to the array

      const arr1=["cat","bat","rat","aat"];
      const arr2=arr1.reverse();
      const length=arr2.push("mat");
      console.log(arr2);
      console.log(arr1);
      console.log(length);
      //output:
      // [ 'aat', 'rat', 'bat', 'cat', 'mat' ]
      // [ 'aat', 'rat', 'bat', 'cat', 'mat' ]
      // 5
    
  • sort() method sorts the elements of an array in place, and returns a reference to the array.

const arr1=[9,1,5,2,8];
const arr2=arr1.sort();
console.log(arr2,arr1);
//[ 1, 2, 5, 8, 9 ] [ 1, 2, 5, 8, 9 ]
  • indexOf(searchElement[,fromIndex]) method gives the index of the first occurrence of the search element in the array

      const a = ['a', 'b', 'a', 'b', 'a'];
      console.log(a.indexOf('b')); // logs 1