Array and Array Methods In JavaScript

Array and Array Methods In JavaScript

What is Array?

The array is a variable that stores the collection of similar or dis-similar elements. It is used when we want to store a list of elements and access them by a single variable. In most languages where the array is a reference to the multiple variables, in JavaScript, an array is a single variable that stores multiple elements.

Declaration of an Array

There are basically two ways to declare an array. Syntax is

let arrayName = [element_1, element_2 ..., element_n]; // method 1
let arrayName = new Array(element_1, element_2, ..., element_n); // method 2

Generally, method 1 is mostly used and we are going to use method 1 in this article.

Initialization of an Array

let fruits = ["Mango","Apple","Orange","Banana"];

Accessing Array Elements

If you want to access the array element, you need to use the index number of that element. For example, if I want to access the "Orange" from array fruits i need the index number of "Orange" which is 2.

let fruits = ["Mango","Apple","Orange","Banana"];
console.log(fruits[2]);

Different Array Methods in JavaScript

There are lots of array methods in javascript, we are going to see all of them. All these methods have their functionality. So let's begin-

Array.push()

The push() method is used to add one or more elements to the end of an array and returns the new length of the array.

let fruits = ["Mango", "Apple", "Orange", "Banana"];
console.log(fruits.push("Pineapple","Watermelon"));
console.log(fruits);

Array.pop()

We can remove an element from an array with the help of pop() method. It removes the last element from an array and returns that element. This method changes the length of the array.

let fruits = ["Mango", "Apple", "Orange", "Banana"];
console.log(fruits.pop());
console.log(fruits);

Array.shift()

The shift() method is very similar to the pop() method except it removes the first element of the array instead of the final element. It returns that removed element and this method changes the length of the array.

let fruits = ["Mango", "Apple", "Orange", "Banana"];
console.log(fruits.shift());
console.log(fruits);

Array.unshift()

The unshift() method is similar to the push() array method while push() adds one or more elements to the end of the Array, the unshift() method adds at the beginning of the array and returns the new length of an array.

let fruits = ["Mango", "Apple", "Orange", "Banana"];
console.log(fruits.unshift("Kiwi","Watermelon"));
console.log(fruits);

Array.indexOf()

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present in the array.

let fruits = ["Mango", "Apple", "Orange", "Banana"];
console.log(fruits.indexOf("Orange")); // present at index 2
console.log(fruits.indexOf("Kiwi"));  // not present

Array.lastIndexOf()

The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present.

let fruits = ["Mango", "Apple", "Banana","Mango","Watermelon", "Grapes"];
console.log(fruits.lastIndexOf("Mango"));

Array.includes()

This method is used to check whether the array contains the specified element or not. It gives true if the element is present in the array otherwise it gives false if the element is not present in the array.

let fruits = ["Mango", "Apple", "Orange", "Banana"];
console.log(fruits.includes("Orange")); // present in array
console.log(fruits.includes("Kiwi")); // not present in array

Array.concat()

The concat() method is used to merge two or more arrays. This method does not change the existing arrays but instead returns a new array.

let fruits = ["Mango", "Apple", "Orange", "Banana"];
let veggies = ["Tomato","Onion","Carrot"]
let iceCream = ['Chocolate','Vanilla']

let combo = fruits.concat(veggies,iceCream);

console.log(combo);

Array.slice()

The slice() method selects the specified number of elements without affecting the original array elements.

let fruits = ["Mango", "Apple", "Orange", "Banana","Pineapple"];

console.log(fruits.slice()); // All elements included
console.log(fruits.slice(2)); // All elements included from index 2
console.log(fruits.slice(1,3)); // All elements included from index 1 to 3(3 not included)

console.log(fruits);

Array.splice()

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

let fruits = ["Mango","Apple"];
console.log(fruits.splice(1,0,"Kiwi","Watermelon")); // inserting "KiWi", "Watermelon" from index 1 without removing(0) any elements
console.log("Updated Fruits : ", fruits);

fruits = ["Mango", "Apple","Banana"];
console.log(fruits.splice(1,1,"Cherry")); // replacing index 1 element "Apple" to "Cherry"
console.log("Updated Fruits : ", fruits);

fruits = ["Mango", "Apple", "Banana","Watermelon","Grapes"];
console.log(fruits.splice(1,3));    // removing 3 elements from index 1
console.log("Updated Fruits : ", fruits);

Array.sort()

The sort() method is used to arrange the array elements in some order. By default, sort() method follows the ascending order.

let fruits = ["Mango", "Apple", "Banana", "Watermelon", "Grapes"];
let nums = [2,1,3,5,4,6];


console.log("Fruits :",fruits.sort());
console.log("Nums :",nums.sort());

Array.reverse()

The reverse() method changes the sequence of elements of the given array and returns the reverse sequence. This method also made the changes in the original array.

let fruits = ["Mango", "Apple", "Banana", "Watermelon", "Grapes"];
let nums = [2,1,3,5,4,6];

console.log("Fruits :",fruits.reverse());
console.log("Nums :",nums.reverse());

Array.map()

The JavaScript array map() method calls the specified function for every array element and returns the new array. This method doesn't change the original array.

let nums = [1,4,9,16,25,36,49,64,81,100];

let sqrtOfNums = nums.map(Math.sqrt);

console.log("Nums :",sqrtOfNums);

Array.fill()

The fill() method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length). It returns the modified array.

let nums = [1,2,3,4,5,6];
console.log(nums.fill(1));  // fill 1 in place of all element place

nums = [1, 2, 3, 4, 5, 6];
console.log(nums.fill("React",2))   // filling "React" from index 2 to end

nums = [1, 2, 3, 4, 5, 6];
console.log(nums.fill("JS",1,4));   // filling "JS" from index 1 to 4(excluding 4)

Array.split()

The split() method takes a pattern and divides a String into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.

let quote = "It always seems impossible until it's done";

console.log(quote.split(" "));

Array.join()

The JavaScript Array join() Method is used to join the elements of an array into a string. The elements of the string will be separated by a specified separator and its default value is a comma(,). It doesn't change the original array.

let nums = [1,2,3,4,5];

console.log(nums.join());    // joining the elements with default comma(,)
console.log(nums.join("And"));  // joining the elements with "And"

console.log(nums);

for of Method

For of method simply iterate over the array one by one, that's all.

Example:

// for of Method
let upperName = ["atul", "singh"];
let pus = [];
for (const iterator of upperName) {
  pus.push(iterator.toUpperCase());
}
console.log(pus); //[ 'ATUL', 'SINGH' ]

Break and continue

Break simply means to get out of the flow.

Example:


for (let i = 0; i < 10; i++) {
   if (i == 3) {
     // console.log(i);
     break; // simply break  out of the block
   }
   console.log(i);
  }

continue

Simply continue means to skip at that point where will check the condition and continue to looping.

Example:


for (let i = 0; i < 6; i++) {
  if (i == 3) {
    // console.log(i);
    continue; // skip
  }
  console.log(i);
}

isArray Method arrayName.isArray( )

Is the array method checking whether the inside pass value is an array or not, in the output it gives the boolean value(true or false)?

isArray() Syntax

The syntax of the isArray() method is: Array.isArray(array variable name)

Example:


// isArray() Method 
let num = [1, 2, 3, 4]; console.log(Array.isArray(num)); // true 
// passing an simple variable 
let num1 = 2; console.log(Array.isArray(num1)); // false 
// passing an empty array 
console.log(Array.isArray([])); // true

// we created an array with element 5 and passed that value to isArray() 
console.log(Array.isArray(new Array(5))); // true 
//passing undefined value to isArray() 
console.log(Array.isArray(undefined)); // false