Arrays & its methods in JavaScript

Arrays & its methods in JavaScript

Introduction to JavaScript

JavaScript is a scripting language and we all know that it is very different from any other programming language. JavaScript is mostly referred to as JS and is a very powerful language. The functionalities of websites and web apps are generally implemented using JavaScript. JavaScript can be used to create games and write server-side logic, the JS frameworks like ReactNative can be used to create mobile apps. Popular JS frameworks that are used to create the front-end of web apps are React, Angular, Vue etc. The websites we use daily use JS under the hood to enhance the user experience. Some of the famous websites that use JS are YouTube, Twitter, Flipkart, Amazon etc.

Arrays

Arrays are used to store a set of items in a single variable, but it is slightly different in JS from other languages. In general, when we talk about an array, we consider it as a container that stores a set of items of the same data types, but that is not true in the case of JavaScript, In JS we can store different datatypes in an array. For example:

let arr = [1, 'a', true, 'string']
console.log(arr)

Output:

In the case of other languages like C++, Java etc we can't store elements of different datatypes in a single array. Otherwise, we will get unexpected output.

#include <iostream>
using namespace std;
int main(){
    int arr[4] = {1, 2, 3, 4};
    for(int i = 0; i < sizeof(arr)/sizeof(arr[0]); i++){
        cout << arr[i] << " ";
    }
    return 0;
}

In an array, the elements are stored at continuous indexes starting from 0. We can access the desired element by their respective index, like

let nums = [23, 45, 56, 67, 78]
console.log(nums[2])

The above will give the element stored at the 2nd index i.e. 56. The elements stored in the array nums will have the indices as shown below.

0 -> 23, 1 -> 45, 2 -> 56, 3 -> 67, 4 -> 78

Different Array Methods

There are multiple predefined array methods for different purposes. Some of the array methods are explained below.

length

To get the length of an array we can use the length function, the array methods can be accessed by using the period(.) symbol.

let names = ["Name1", "Name2", "Name3", "Name4"]
console.log(names.length)

Output: 4

push

The push method is used for adding a new element in the array, it adds the element after the element at the last index.

let fruits = ["Apple", "Orange", "Guava", "Pineapple"]
fruits.push("Strawberry")
console.log(fruits)

pop

pop method pops out the last element from the array.

let selectedColors = ['Red', 'Green', 'Blue', 'Aqua', 'Orange']
console.log(selectedColors)

Output :

['Red', 'Green', 'Blue', 'Aqua', 'Orange']

selectedColors.pop()
console.log(selectedColors)

Output :

[ 'Red', 'Green', 'Blue', 'Aqua' ]

The last element is popped out from the array selectedColors.

indexOf

The indexOf method is used for getting the index of the array's elements.

let fruits = ['Mango', 'Apple', 'Orange', 'Banana']
console.log(fruits.indexOf('Apple'))

Output :

1

In the fruits array, the 'Apple' is stored at the first index so the indexOf method returns the value 1.

join

join concatenates all the elements of the array, using the string provided and returns it.

let fruits = ['Mango', 'Apple', 'Orange', 'Banana']
console.log(fruits.join('-'))

Output :

Mango-Apple-Orange-Banana

All the elements of the fruits array are joined using '-' and a single string is returned.

slice

The slice method will return a shallow copy of the array, the original array will not be modified. It gives a part of the original array. We have to provide the first index from where the slicing of the array element will be started and the second parameter tells where to end. There are multiple ways to slice the elements. The other ways are explained below.

The syntax will look like :

console.log(array.slice(start, end)) 
console.log(array.slice(n) // Where n = number of elements

When we slice the elements the starting elements are sliced, and the end indexed element will not be included.

Example :

let arr1 = [1, 2, 3, 4, 5, 6, 7]
console.log(arr1.slice(1, 3)) 
console.log(arr1.slice(2))
console.log(arr1)

Output :

[ 2, 3 ]

[ 3, 4, 5, 6, 7 ]

[ 1, 2, 3, 4, 5, 6, 7 ]

We can see that in the output, the original array arr1 remains intact, while a copy of it is being created while we are slicing it from the original.

reverse

The reverse method reverses the elements of the array, the important point to know is that it doesn't make the changes in a new copy, it modifies the original array.

let nums = ['one', 'two', 'three', 'four']
console.log(nums.reverse())
console.log(nums)

Output :

['four', 'three', 'two', 'one']

['four', 'three', 'two', 'one']

splice

The splice method is used for inserting or replacing an element from the array. It accepts the start index, how many elements to delete and the element that has to be added, these three things as parameters.

Syntax :

console.log(array.splice(start, deleteCount, 'New element'))

Examples :

let birds = ['Peacock', 'Sparrow', 'Crow', 'Parrot', 'Pigeon']
console.log(birds.splice(1, 0, 'Eagle'))
console.log(birds)

Output :

[]

[ 'Peacock', 'Eagle', 'Sparrow', 'Crow', 'Parrot', 'Pigeon' ]

birds.splice(1, 4, '***')
console.log(birds)

Output :

[ 'Peacock', '***', 'Pigeon' ]

The elements from the first index onwards are replaced with '***', and the four elements are replaced.

lastIndexOf

As the name suggests it is used when we have duplicate elements and we have to find the last index of the element in an array.

Example :

let evenNums = [2, 4, 6, 8, 2, 10, 2, 12, 14, 16, 2]
console.log(evenNums.indexOf(2))
console.log(evenNums.lastIndexOf(2))

Output :

0

10

In the above array '2' appears multiple times so lastIndexOf returns the index at which the '2' is appeared last. The main difference between indexOf and lastIndexOf is that indexOf returns the index when it encounters the element first time while lastIndexOf searches for the last appearance.

includes

Check whether a certain value is present in the array or not, it returns true or false.

let names = ['Saurav', 'Kriti', 'Keshav', 'Shruti']
console.log(names.includes('Keshav'))
console.log(names.includes('Kesari'))

Output :

true

false

There are a lot of array methods that can be used with the array.

For a more detailed explanation, visit mdn documentation.