Array in JavaScript (JS)
How to create an array in JavaScript (JS) ?
Array is nothing but collection of similar datatypes. Creating an array is as simple as creating a variable in JS.
let a = [2,4,6,8,10] // array of integers
let b = ["Sun", "Mon", "Tue", "wed"] // array of strings
console.log(a) // output : [ 2, 4, 6, 8, 10 ]
console.log(b) // output : [ 'Sun', 'Mon', 'Tue', 'wed' ]
Accessing elements from array
Array element can be accessed by referring to the index number. Array index always starts with 0.
// Consider an example of adding elements to an existing array
let a = [2,4,6,8,10] // array of integers
a[5] = 12 // adding new element at index 5
console.log(a) // output : [ 2, 4, 6, 8, 10, 12 ]
// New element can be added at any index in the array
let a = [2,4,6,8,10]
a[9] = 20 // adding new element at index 9
console.log(a) // output : [ 2, 4, 6, 8, 10, <4 empty items>, 20 ]
// Here elements from index 5 to 8 are empty, while new element is added at index 9
// Consider an example of retreiving elements from an existing array
console.log(a[9]) // Accessing element from index 9
// output : 20
Array length
let b = ["Sun", "Mon", "Tue", "wed"]
console.log(b.length) // output : 4
Array basic operations
We can perform certain basic operations on an array such as adding element at the end of an array, removing first element.
// Add one or more elements to the end of an array
let a = [5, 10, 15, 20]
a.push(50, 55) // adding elements at the end of an array
console.log(a) // output : [ 5, 10, 15, 20, 50, 55 ]
// Remove last element from the array
let a = [5, 10, 15, 20]
a.pop() // removing last element from the array
console.log(a) // output : [ 5, 10, 15 ]
// Add one or more elements to the start of the array
let a = [5, 10, 15, 20]
a.unshift(3,4) // adding elements at the start of an array
console.log(a) // output : [ 3, 4, 5, 10, 15, 20 ]
// Remove first element from an array
let a = [3, 4, 5, 10, 15, 20]
a.shift() // removing first element from an array
console.log(a) // output : [ 4, 5, 10, 15, 20 ]
Searching elements in the array
In an array, if you want to search for a specific element then there are three methods – INCLUDES, INDEXOF & LASTINDEXOF
// Search element in array - INCLUDES
// 'includes' method returns true if array contains a given element
// 'includes' method returns false if element is not found in the array
// 'includes' method is case sensitive
let a = ["Ram", "Suresh", "Mayur"]
console.log(a.includes("Swapnil")) // output : false
// Find index of particular element in the array - INDEXOF
// indexOf() method returns the index of first match for a specified value
// indexOf() method returns -1 if the value is not found in the array
// By default the search starts at the first element and ends at the last.
let a = ["Ram", "Suresh", "Mayur", "Swapnil", "Mayur"]
console.log(a.indexOf("Mayur")) // output : 2
console.log(a.indexOf("Indrasen")) // output : -1
// Find last index of particular element in the array - LASTINDEXOF
// lastIndexOf() method returns the last index of a match for a specified value
// indexOf() method returns -1 if the value is not found in the array
// By default the search starts at the last element and ends at the first.
let a = ["Ram", "Suresh", "Mayur", "Swapnil", "Mayur"]
console.log(a.lastIndexOf("Mayur")) // output : 4
Commonly used array operations
Common array operations includes converting an array into string, reversing an array, converting string into array & getting section of an array etc.
// Converting an array into string
let a = ["Ram", "Suresh", "Mayur", "Swapnil"]
console.log(a.join("_")) // output : Ram_Suresh_Mayur_Swapnil
// Getting string representation of an array
console.log(a.toString()) // output : Ram,Suresh,Mayur,Swapnil
// Difference between join() and toString() is we can provide delimiter to join()
// Converting a string into an array
let s = "I_Love_JS"
console.log(s.split("_")) // output : [ 'I', 'Love', 'JS' ]
// Reversing an array
let s = ["Red", "Blue", "Green"]
console.log(s.reverse()) // output : [ 'Green', 'Blue', 'Red' ]
// Getting some portion of an array
let s = ["Red", "Blue", "Green", "Black", "Orange"]
console.log(s.slice(2)) // slicing an array from index 2
// output : [ 'Green', 'Black', 'Orange' ]
// Slicing an array with start and end index
let s = ["Red", "Blue", "Green", "Black", "Orange"]
console.log(s.slice(2,4)) // slicing an array from index 2 to index 3 but we mentioned 4 because end index is not inclusive so always need to provide 'end_index+1'
// output : [ 'Green', 'Black' ]
For...of loop : For every item of an array
For…of loop is used to iterate over an array. To iterate ‘every item of’ an array, this loop is useful.
Difference between ‘For…in’ & ‘For…of’ loop is, ‘For…in’ loop is used to iterate properties of an object while ‘For…of’ loop is used to iterate a collection like an array or a list.
let colors = ["Red", "Blue", "Green", "Black", "Orange"]
for (const item of colors) {
console.log(item)
}
// output :
Red
Blue
Green
Black
Orange
For...each loop on array
For…each loop is used to create and execute a function for each item of an array.
This is very powerful programming aspect of JavaScript.
// Creating & executing a function using For...each for every element of an array
let numbers = [2, 4, 6 , 8, 10]
numbers.forEach(function (item){
console.log(10 * item) // multiplying every element of an array by 10
})
// output :
20
40
60
80
100
// Index of every element along with an entire array can also be passed to this function
let numbers = [2, 4, 6 , 8, 10]
numbers.forEach(function (item, index, numbersArray){
console.log("Multiplying "+item+" by 10 = "+10*item+ " at index :"+ index +" complete array :"+numbersArray)
})
// output :
Multiplying 2 by 10 = 20 at index :0 complete array :2,4,6,8,10
Multiplying 4 by 10 = 40 at index :1 complete array :2,4,6,8,10
Multiplying 6 by 10 = 60 at index :2 complete array :2,4,6,8,10
Multiplying 8 by 10 = 80 at index :3 complete array :2,4,6,8,10
Multiplying 10 by 10 = 100 at index :4 complete array :2,4,6,8,10
Assignments :
- Write a program to reverse an array of numbers without using reverse array function.
- Write a program to remove duplicate elements from an array.
- Write a program that makes a shallow compare of two arrays and returns true if they are identical. Expected Result: ([1, 2, 3], [1, 2, 3]) => true
- Consider an array, let names = [“Ratnesh“, “Swapnil”, “Mayur”, “Indrasen”]
- Write a function to remove “Ratnesh” from the array.
- Write a function to remove “Indrasen” from the array.
- Write a function to add “Russell” to the front of the array.
- Write a function to add your name to the end of the array.
- Write a program to iterate given array, and print the total number of characters in each name.