Arrays in Javascript With Code Snippets

Arrays in Javascript With Code Snippets

Arrays store more than one value and can be of any data type. The array is created with the help of a square bracket. The size of an array is not fixed we can increase and decrease the size of an array as per our requirements. Each element of an array is specified by an index

Javascript allows us to store multiple values in an array and that can be of any datatype which is a little bit different from other languages

Array Indexing:

The indexing concept is available in the array. we can fetch specific elements based on their index position.

let playerNames = ['Rohit','Virat','Surya','Hardik','KlRahul','Jadeja']
console.log(playerNames[0])  - Rohit
console.log(playerNames[1])  - Virat
console.log(playerNames[2])  - Surya
console.log(playerNames[3])  - Hardik
console.log(playerNames[4])  - KlRahul
console.log(playerNames[5])  - Jadega

//changing the value of specific elements based on their index.
playerNames[0] = "Rohit Sharma"
playerNames[1] = "Virat Kohli"
console.log(playerNames)

//Output
[
  'Rohit Sharma', 'Virat Kohli', 'Surya', 'Axar Patel', 'MsDhoni',
  'KlRahul','jadega','Tendulkar'
]

//typeof
console.log(typeof playerNames)
Output
------
object

if you want to know whether the array you have created is actually an array or not so for that  there is an array function called isArray()

console.log(Array.isArray(playerNames))

Length Of An Array:

The length of an array tells us how many elements are present there in the Array, the length will always start from 1 to the number of elements present inside an array.

array_One = [10,20,30,40,'deepak',true]
console.log(array_One)

Output
------
6

Array Push Method:

This method is used to add elements to an array and that too in the end.

syntax
-------
arrayname.push('elements')

let playerNames = ['Rohit','Virat','Surya','Hardik','KlRahul','Jadeja']
playerNames.push('Dhoni', 'Yuvraj')
console.log(playerNames)

Output
------
[
  'Rohit',   'Virat', 
  'Surya',   'Hardik',
  'KlRahul', 'Jadeja',
  'Dhoni',   'Yuvraj' 
]

the array is mutable so when I am applying the push method to an array, then the changes were being made on the original array.

Array Pop Method:

The pop method of the array is used to remove the last element. after removing the element from an array the original array will get modified, which means the changes were being reflected in the original array.

let playerNames = [
  'Rohit',   'Virat', 
  'Surya',   'Hardik',
  'KlRahul', 'Jadeja',
  'Dhoni',   'Yuvraj' 
]
poppedplayarName= playerNames.pop()
console.log(poppedplayarName)
console.log(playerNames)

Output
-------
Yuvraj
[
  'Rohit',   'Virat',
  'Surya',   'Hardik',
  'KlRahul', 'Jadeja',
  'Dhoni'
]

Pop not only remove the last index value from the array but also return that value that is being removed by the pop method.

console.log(playersNames.pop())

Array Unshift Method:

Unshift will add elements to the beginning of the array, The changes will reflect to the original array.

syntax:
arrayname.unshift('elementname)

let playerNames = [
  'Rohit',   'Virat', 
  'Surya',   'Hardik',
  'KlRahul', 'Jadeja',
  'Dhoni',   'Yuvraj' 
]
playerNames.unshift('Subhman Gill')
console.log(playerNames)

Output
------
[
  'Subhman Gill', 'Rohit',  'Virat', 'Surya','Hardik','KlRahul','Jadeja',
  'Dhoni','Yuvraj'
]

Array Shift Method:

This method is used to remove the first element from an array.

syntax:
arrayname.shift()

let playerNames = [
  'Rohit',   'Virat', 
  'Surya',   'Hardik',
  'KlRahul', 'Jadeja',
  'Dhoni',   'Yuvraj' 
]
playerNames.shift()
console.log(playerNames)

Output
------
[
  'Virat',  'Surya',  
  'Hardik', 'KlRahul',
  'Jadeja', 'Dhoni',  
  'Yuvraj'
]

shift array method will also return the value it is removing from the array just like the pop method , the pop method also removes from the end and return the value.

Note: push and pop is fast as compared to shift and unshift

Array Slice Method:

The slice method is used to fetch multiple values from an array, the slicing is done using an index number, slices takes two argument

  • 1st one from where we need to select the element for example if we have specefied 1 then it will select the element from index1.

  • 2nd one is the ending value but it doesn't include the ending argument it will always consider [ending_value-1] for example if we have written 4 as the ending argument then it will select up to ending-1 i.e 3

the slice also returns a new array it doesn't change the existing arrays.

let playerNames = ['Rohit','Virat','Surya','Hardik','KlRahul','Jadeja']
let result = playerNames.slice(1,3)
console.log(result)

Output
-------
[ 'Virat', 'Surya' ]

playerNames.slice(starting_index, ending_index)
1 is here starting index         [1]
2. ending index[endingValue-1]   [3-1]

Array Splice Method:

The splice method is used to create, delete, and update the elements in the array, we can perform curd operations with the help of splice method.

const city = ['Mumbai','Delhi','Gurugram','Chennai','Hyderabaad']
city.splice('4',0,'Pune','Nashik','Jaipur')
console.log(city)

Output
-------
[
  'Mumbai',   'Delhi',   
  'Gurugram', 'Chennai', 
  'Pune',     'Nashik',  
  'Jaipur',   'Hyderabad'
]

4: I want to start from index-4
0: I don't want to delete any elements if I specify 1 then hyderabaad will be deleted.
'Pune','Nashik','Jaipur': these are the elements I want to add.
// add javascript to the end of an array using splice
const Lang = ['Python','Django','RestApi','HTML','CSS']
const newLang = Lang.splice(Lang.length+1,0,'Javscript','MongoDB')
console.log(Lang)

Output
------
['Python', 'Django', 'RestApi','HTML', 'CSS', 'Javscript','MongoDB']

// 
const Lang = ['Python','Django','RestApi','HTML','CSS']
const newLang = Lang.splice(Lang.length,0,'Javscript','MongoDB')
console.log(Lang)

['Python', 'Django', 'RestApi','HTML', 'CSS', 'Javscript','MongoDB']

Note: splice is something which is mostly used for deleting. if you are not deleting something then the return value of the splice will be [ ]. but if we are deleting something then it will return that deleted value instead of returning an empty array.

// returning deleted splice value
const Lang = ['Python','Django','RestApi','HTML','CSS']
const newLang = Lang.splice(4, 1,'Javscript','MongoDB')
console.log(Lang)
console.log(newLang)

Output
------
[ 'Python', 'Django', 'RestApi', 'HTML', 'Javscript', 'MongoDB' ]
[ 'CSS' ]

Array Concatenation method:

The Concatenation is used to join one or more arrays and it returns a new array but it does not change the existing arrays

let arrayOne = [1,2,3,4]
let arrayTwo = [5,6,7]
console.log(arrayOne.concat(arrayTwo))


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

Array Fill Method:

The fill method is used to fill the values it works based on the index number. In fill method, the original array is getting modified.

let arrayOne = [1,2,3,4,5,6,7,8,9,10]
let result = arrayOne.fill('deepak', 2,5)
console.log(result)
console.log(arrayOne)

Output
------
[1, 2, 'deepak', 'deepak','deepak', 6, 7,8, 9, 10 ]
// the original array is also getting modified
[1, 2, 'deepak', 'deepak','deepak', 6, 7,8, 9, 10 ]

deepak is the value I wanted to fill.
2,5 is the index number from where up to where I wanted to fill so it will fill from index 2 to 4. (5 will be exclusive)

Array Includes method:

This method will check whether the element is present or not. it gives us the result based on the boolean value if the value is present then we will get true as the result else we will get false.

let array = [1,2,3,4,5,6,7,8,9,10]
console.log(array.includes(7))
console.log(array.includes(11))

Output
------
true
false

Array indexof Method

  • The indexof method will fetch the index of a particular element, but if you are having similar element/ same element in an array multiple numbers of times then it will pick the first index of that element. but if we want to know the index of that element that is not present in the array then we will get -1

  • we can also specify from where we need to start searching for example let array = [1,2,3,4,5,6,7,8,9,1,2,3,5,3,4,5] console.log(array.indexOf(5, 5))

    Output : 12

    console.log(arrayindexOf(5))

    Output: 7

let array= [1,2,3,4,5,6,3,4,5,2,3,4,7,8,]
console.log(array.indexOf(5))

Output
------
4
// in this example 5 is present here multiple times but still, it will only pick the first index of that element.

let array = [1,2,3,4,5,6,3,4,5,2,3,4,7,8,]
console.log(array.indexOf(10))

Output
------
-1

Array Last Index of Method:

the last index will work opposite of index-of, index-of we are getting the 1st index if there is a repetition of that particular element but in the lastIndex-of method, we will get the lastIndex it will pick the last-index, not the fist-index lets go through an example for more clarity.

Note: here also we will get -1 if we want to fetch the index of an element that is not present inside the array.

let array = [1,2,3,4,5,6,7,8,9,10,12,11,10,10,34]
console.log(array.lastIndexOf(10))

Output
------
13

Is Array Method:

The isArray() method will check whether the value we have passed is an array or not. It gives us the result in the boolean form if the value we have passed is an array then it will give us true otherwise false.

let arrayOne = [1,2,3,4,5,6,7,8,9,10]
let arrayThree =[1,2,3,4,['Deepak', 'Kumar', 'Nayak']]

Output
-------
true
true

Array Join Method:

The join() method in an array will return a new string by joining the elements present inside an array with the help of a separator.

let arayOne = [10,20,30,40,50,60,70]
let result = arayOne.join(" | ")
console.log(result)
console.log(typeof result)

Output
------
10 | 20 | 30 | 40 | 50 | 60 | 70
string # return a new string

Map Method in Array:

The map method is applied to every element present inside an array, it returns a new array, and no changes will be done to the original array.

let array_One = [1,4,16,25,36,49,64,81,100]
console.log(array_One.map(Math.sqrt))

console.log(array_One)

Output
------
[1, 2, 4, 5, 6,7, 8, 9, 10]
#map gives us a new result.

[1,  4, 16,  25, 36, 49, 64, 81, 100] 
# originalArray which is not getting modified

Array Reverse Method:

This method in the array will reverse the entire array and the changes will also get reflected in the original array.

let array_One = [10,20,30,40,50,60,70]
let result = array_One.reverse()

console.log(result)
console.log(array_One)

Output:
--------
[70, 60, 50, 40, 30, 20, 10 ]
[70, 60, 50, 40, 30, 20, 10]

Array Sort Method

The sort method will sort all the elements in the array in alphabetical order and that too in descending order. Here the changes are being made to the original array

let userNames = ['anirudh','abhinash','deepak','rohan','vivek', 'xara', 'bubul']
console.log(userNames.sort())

Output
------
['abhinash', 'anirudh', 'bubul', 'deepak', 'rohan', 'vivek', 'xara']

Note: if I have written that the changes are being made to the original array then please check it by yourself by printing the original_array, here in the above example you can print userNames so that you can get to know the result by yourself.

For-of-Loop in Array:

The for-of loop is designed for the array. it loops through the elements stored inside an array. you can also use for-of loops in strings, maps etc.

let arrayOne = ['one','two','three','four','five','six','seven','eight']
let arrayCap = []

for(let element of arrayOne){
  arrayCap.push(element.toUpperCase())
}

console.log(arrayCap)

Output
-------
['ONE',   'TWO', 'THREE', 'FOUR','FIVE',  'SIX', 'SEVEN', 'EIGHT']

How to Clone an Array:

let arrayOne = [10,20,30,40]
let arrayTwo = [10,20,30,40]

so this is the very basic way of cloning an array what does actually clone mean, it means creating a copy.

if I am doing any changes to arrayTwo then the changes will not reflect to arrayOne.

let arrayOne = [10,20,30,40]
let arrayTwo = [10,20,30,40]

arrayTwo.push(50,60)
console.log(arrayTwo)
console.log(arrayOne)

Output
-------
[ 10, 20, 30, 40, 50, 60 ]
[ 10, 20, 30, 40 ]

Note: this is not the right way to clone an array because if we are having a lot of items in the array this will not he helpful... so lets study another way how to clone an array

2nd Way Of Cloning an Array By using Concat:


let arrayOne = [10,20,30,40]
let arrayTwo = [].concat(arrayOne)
console.log(arrayTwo)
console.log(arrayOne)

here also it will act in the same way if I will do any changes to arrayTwo it will not reflect to arrayOne

3rd way of cloning an array is by using the spread operator:

let arrayOne = [10,20,30,40]
let arrayTwo = [...arrayOne]
console.log(arrayTwo)

Output
------
[ 10, 20, 30, 40 ]

here also if I am doing any changes to arrayOne the changes will not reflect to arrayTwo