Arrays in Javascript

Arrays in Javascript

In this blog, you'll learn about JavaScript arrays and their operations.

Arrays

In JavaScript, an array is a special variable that can store different data types and also allows to store duplicates elements. Each value is called an element specified by an index.

Creating JavaScript Arrays

There are three ways to create an array.

1. Using array constructor

let num= new Array()

The num array is empty which does not hold any elements.

  • If we know the number of elements that the array will hold , then we create the array with initial size.
let names=Array(19)
  • If we want to create an array and initialise with some elements, then create as follows:
let country=new Array("India","USA", "Russia");

2. Using square brackets[ ] (or, Array Literal Notation)

This is the most preferred way to create an array. We use square brackets ([ ]) to wrap a comma separated list of elements.

let arr=[1,2,3,4]

3. Using split

We can split a string at different positions and then change to an array. Lets see the examples below:

let course='JavaScript'
const courseArr=course.split('')
console.log(courseArr) //["J","a","v","a","S","c","r","i","p","t"]

Accessing JavaScript array elements using index

An array index starts from 0. To access an element in an array, we specify an index in the square brackets [ ].

let companies=['Amazon', 'Google', 'Netflix']
console.log(companies[2]) // 'Netflix'

Modifying array element

An array is mutable(modifiable). We can change the value of an element in an array. Lets see the code example below:

let nums=[1,2,3,4,5]
nums[0]=10
nuts[3]=20
console.log(nuts) // [10,2,20,4,5]

Methods to manipulate array

1. length()

  • To know the size of an array
let numbers=[1,2,3,4,5]
console.log(numbers.lenght) // 5

2. indexOf()

  • To check if an element exist in an array. If it exists, it returns the index of the element else return -1.
let arr=['Amazon', 'Netflix', 'Uber']
console.log(arr.indexOf('Uber'))   //2

3. lastIndexOf()

  • It returns the index of the last element in the array, if it exist else returns -1.
let companies=['Amazon', 'Netflix', 'Uber','Apple']
console.log(companies.lastIndexOf('Uber'))   //2
console.log(companies.lastIndexOf('Infosys'))   //-1

4. Array.isArray()

  • To check if the given data is an array or not. It returns boolean(true or false).
let companies=['Amazon', 'Netflix', 'Uber','Apple']
console.log(Array.isArray(companies)) //true

let number=8
console.log(Array.isArray(number)) //false

5. toString()

  • It converts array to string
let companies=['Amazon', 'Netflix', 'Uber','Apple']
console.log(companies.toString()) // Amazon,Netflix,Uber,Apple

6. concat()

  • It concatenates two arrays.
let companies=['Amazon', 'Netflix', 'Uber','Apple']
let location=['USA', 'India','UK']
let companiesLocation=companies.concat(location)
console.log(companiesLocation) //['Amazon', 'Netflix', 'Uber','Apple','USA', 'India','UK']

7. join()

  • It is used to join the elements of the array, the argument we passed in the join method will be joined in the array and return as a string. By default, it joins with a comma, but we can pass different string parameter which can be joined between the items.
let companies=['Amazon', 'Netflix', 'Uber','Apple']
console.log(companies.join()) //Amazon,Netflix,Uber,Apple
console.log(companies.join('')) //AmazonNetflixUberApple
console.log(companies.join(' ')) //Amazon Netflix Uber Apple
console.log(companies.join('#')) //Amazon # Netflix # Uber # Apple
console.log(companies.join(,)) //Amazon,Netflix,Uber,Apple

8. fill()

  • It fills the array elements with a static value.
let values=Array(5).fill('Y') //[Y,Y,Y,Y,Y]

9. push()

  • To add an element to the end of an existing array.
let companies=['Amazon', 'Netflix', 'Uber','Apple']
companies.push('Meta')
console.log(companies) // ['Amazon', 'Netflix', 'Uber','Apple','Meta']

10. pop()

  • To remove an element from the end of the existing array.
let companies=['Amazon', 'Netflix', 'Uber','Apple']
companies.pop() // remove an element from the end
console.log(companies) // ['Amazon', 'Netflix', 'Uber']

11. unshift()

  • To add an element to the beginning of an existing array.
let companies=['Amazon', 'Netflix', 'Uber','Apple']
companies.unshift('Meta')
console.log(companies) // ['Meta','Amazon', 'Netflix', 'Uber','Apple']

12. shift()

  • To remove an element from the beginning of an existing array.
let companies=['Amazon', 'Netflix', 'Uber','Apple']
companies.shift() // remove an element from the beginning
console.log(companies) // ['Netflix', 'Uber','Apple']

13. reverse()

  • It reverse the order of an array.
let numbers=[1,2,3,4,5]
numbers.reverse() 
console.log(numbers) //[5,4,3,2,1]

14. sort()

  • It arrange array elements in ascending order.
let companies=['Amazon', 'Netflix', 'Uber','Apple']
companies.sort()
console.log(companies) //['Amazon','Apple','Netflix','Uber']

15. slice()

  • It returns a new array containing a portion of the array. It takes two parameters: starting and ending position. It doesn't include the ending position.
let companies=['Amazon', 'Netflix', 'Uber','Apple','Meta','Ola']
companies.slice(1,3) //['Amazon','Apple','Meta','Ola']

16. splice()

  • It takes three parameters: starting position, number of times to be removed and elements to be added.
let numbers = [1, 2, 3, 4, 5, 6]
numbers.splice(3, 3, 7, 8, 9)
  console.log(numbers.splice(3, 3, 7, 8, 9))  // -> [1, 2, 3, 7, 8, 9] //it removes three elements and replace with three elements.