Before exploring the array methods in JavaScript, it is essential to have a clear understanding of what an array signifies in the JavaScript programming language...
Array in JAVA Script :
An array in JavaScript is a flexible data structure. It stores multiple values of various data types within a single variable. It acts as a collection, providing storage space for a variety of values including Numbers, Booleans, Strings, Objects, or even other arrays.
Arrays are represented by a pair of square brackets []. The individual values within the array are known as elements and their position is defined by index, which starts from 0. Each element in an array is separated by commas ( , ).
Array Methods in JAVA Script :
JavaScript arrays provide built-in methods that simplify common tasks like adding or removing elements, combining arrays, searching for elements, iterating over array elements, reducing to a single value, and sorting. These methods provide convenient functionality, making it easier for developers to work with arrays and write concise code to achieve their desired outcomes.
Example:
let names = ['Mohan','Gopal','Shyam','Bankebihari','Girdhari','Madhab'];
console.log(names);
Output:
[ 'Mohan','Gopal','Shyam','Bankebihari','Girdhari','Madhab' ]
Array Methods:
1. Push():
This method adds a new element to the end of an array, not the beginning.
Example:
let sports =['Tennis','Football','Badminton','Ctricket','Volleyball'];
sports.push('Hockey');
console.log(sports);
In the provided code, an array is declared by the name "sports" which contains 5 names. The 'push' method is used to add other elements to the end of an array. So, the resulting output is:
[ 'Tennis','Football','Badminton','Ctricket','Volleyball','Hockey']
2.Pop():
This method is used to remove the last element from an array.
Example:
let fruits =['Apple','Mango','Watermelon','Pomegranate','Strawberries'];
fruits.pop();
console.log(fruits);
Here by the pop method, the last item in the array is removed. The resulting output is:
[ 'Apple','Mango','Watermelon','Pomegranate' ]
3.Splice():
This method is used to add or remove elements from an array. It requires two parameters: The first parameter is the starting position, which determines where the changes in the array should begin. This position is specified using an index value, which starts from 0 for the first element in the array. The second parameter defines the number of elements that should be removed from the array.
Example:
let colors =['Red','Green','Blue','Orange','Pink'];
colors.splice(2,2,'Brown','Yellow');
console.log(colors);
Output:
[ 'Red', 'Green', 'Brown', 'Yellow', 'Pink' ]
4.Slice():
This method has two optional parameters: 'start' and 'end'. 'start' parameter specifies the index at which the slicing should begin, and the `end` parameter defines the index at which the slicing should end.
Example:
let cartoon =['Doraemon','Tom and Jerry','Shinchan','Chhota Bheem','
Ninja Hattori','Motu Patlu'];
console.log(cartoon.slice(1,5));
Output:
[ 'Tom and Jerry', 'Shinchan', 'Chhota Bheem', 'Ninja Hattori' ]
5.Concat():
This method is used to merge or combine multiple arrays together.
let names1=['Krishna', 'Mohan', 'Murli', 'Radhey', 'Shyam'];
let names2=['Shyam', 'Madhav' , 'Banke Bihari' ];
console.log(names1.concat(names2));
In the provided code, There are two arrays named `names1` and `names2` and they are merged using the concat method. The resulting output is:
['Krishna','Mohan','Murli','Radhey','Shyam','Shyam','Madhav','Banke Bihari']
6.Fill():
This method allows to replace all the values in an array with a chosen value. By default, it replaces all elements in the array. The second parameter defines a range of elements to replace by specifying the starting and ending position within the array.
Example:
let chocolates =['Snickers','Raffaello','Milk Bar','Amul','Kit Kat'];
chocolates.fill('Cadbury ',1,4);
console.log(chocolates);
Output:
[ 'Snickers', 'Cadbury ', 'Cadbury ', 'Cadbury ', 'Kit Kat' ]
7.Include() :
The `Include ()` method is used to check if a string contains a specified substring. It returns a boolean value TRUE if the substring is found and FALSE if it is not found.
Example :
let juices = ['Amla', 'Pomegranate', 'Pineapple', 'Lemon', 'Cranberry' ];
console.log(juices.includes('Lemon'));
Output :
true
8.Index of() :
The `indexOf() ` method is used to find the position of the first appearance of a value in an array. It returns the index of that value. If the value is not found, it returns -1.
Example:
let days =['Sunday' , 'Monday' , 'Tuesday' , 'Wednesday' , 'Thursday'];
console.log(days.indexOf('Tuesday')); //present at index 2
console.log(days.indexOf('Friday')); //not present in the array
Output:
2
-1
9. Last index of :
The `lastindexOf ` method returns the index of the last appearance of a value within an array. If the value is not found, it returns -1.
Example:
let days =['Sunday' , 'Monday' , 'Tuesday' , 'Wednesday' , 'Thursday' , 'Friday'];
console.log(days.lastIndexOf('Sunday'));
console.log(days.lastIndexOf('Saturday'));
Output:
0
5
10.Is array() ;
is used to check whether a given value is an array. It returns ` true ` if the value is an array, and ` false ` if it is not.
Example:
const array1 = [2, 4, 6];
const array2 = "not an array";
console.log(Array.isArray(array1));
console.log(Array.isArray(array2));
Output:
true
false
11.Join() :
This method combines all the elements of an array into a single string. You can specify a separator of your choice to be inserted between each element while creating the resulting string.
Example:
let chocolates =['Snickers','Raffaello','Milk Bar','Amul','Kit Kat'];
console.log(chocolates.join('&'));
Output:
Snickers&Raffaello&Milk Bar&Amul&Kit Kat
12.Map() ;
This method creates a new array by calling a provided function on each element of the calling array.
Example :
let n1 = [1,4,9,16,25,36,49,64,81,100];
let n2 = n1.map(Math.sqrt);
console.log(n2);
Output :
[
1, 2, 3, 4, 5,
6, 7, 8, 9, 10
]
13.Reverse() ;
This method in JavaScript is used to reverse the order of elements in an array.
Example :
let planets =['Mercury','Venus','Earth',' Mars','Jupiter'];
console.log(planets.reverse());
Output :
[ 'Jupiter', ' Mars', 'Earth', 'Venus', 'Mercury' ]
14. Shift ;
This method removes the first element from an array and then shifts all the other elements down, so the second element becomes the first, the third becomes the second, and so on.
Example :
let cricketers =['Dhoni','Sachin','Rohit','Rahul'];
cricketers.shift('');
console.log(cricketers);
Output :
[ 'Sachin', 'Rohit', 'Rahul' ]
15.Un shift() ;
This method is used to insert one or more elements at the beginning of an array. It's like adding new items at the start of an array.
Example:
let actors = ['Salman','Aamir','Amitabh','Shahrukh','Htithik'];
actors.unshift('Kartik');
console.log(actors);
Output :
[ 'Kartik', 'Salman', 'Aamir', 'Amitabh', 'Shahrukh', 'Htithik' ]
16.Sort() ;
The sort() method can be used to sort an array's elements in ascending or descending order.
Example:
let days= [ 'Sunday' , 'Monday' , 'Tuesday' , 'Wednesday' , 'Thursday' , 'Friday' , 'Saturday' ];
console.log(days.sort( ));
Output :
[ 'Friday', 'Monday', 'Saturday', 'Sunday', 'Thursday', 'Tuesday', 'Wednesday' ]
17.Split() ;
This method divides a string into smaller parts based on a given pattern.
Example:
let lines='The Key to happiness is the reduction of desires';
console.log(lines.split(' '));
Output:
[ 'The','Key','to','happiness','is','the','reduction', 'of','desires' ]