It’s recommended to go through Arrays in JavaScript. JavaScript array contains some built-in properties that every JavaScript developer should know how to use and when or where to use them. We can use them to add, remove, iterate, or manipulate data as per our requirements.
We will be discussing the following array methods:
- Javascript Array.push() Method
- Javascript Array.unshift() Method
- JavaScript Array.pop() Method
- JavaScript Array.shift() Method
- JavaScript Array.splice() Method
- JavaScript Array.slice() Method
- JavaScript Array some() Method
- JavaScript Array reduce() Method
- JavaScript Array map() Method
Method 1: Javascript Array.push() Method
Adding Element at the end of an Array. As arrays in JavaScript are mutable objects, we can easily add or remove elements from the Array. And it dynamically changes as we modify the elements from the array.
Syntax :
Array.push(item1, item2 …)
Parameters: Items to be added to an array.
Example: In this example, we will be adding new elements such as some numbers and some string values to the end of the array using the push() method.
JavaScript
// Adding elements at the end of an array // Declaring and initializing arrays let number_arr = [10, 20, 30, 40, 50]; let string_arr = [ "piyush" , "gourav" , "smruti" , "ritu" ]; // push() // number_arr contains [10, 20, 30, 40, 50, 60] number_arr.push(60); // We can pass multiple parameters to the push() // number_arr contains // [10, 20, 30, 40, 50, 60, 70, 80, 90] number_arr.push(70, 80, 90); // string_arr contains // ["piyush", "gourav", "smruti", "ritu", "sumit", "amit"]; string_arr.push( "sumit" , "amit" ); // Printing both the array after performing push operation console.log( "After push op " ); console.log(number_arr); console.log( "After push op " ) console.log(string_arr); |
After push op [ 10, 20, 30, 40, 50, 60, 70, 80, 90 ] After push op [ 'piyush', 'gourav', 'smruti', 'ritu', 'sumit', 'amit' ]
Method 2: Javascript Array.unshift() Method
This method is used to add elements to the front of an Array.
Syntax :
Array.unshift(item1, item2 …)
Parameters: Items to be added to the array
Example: In this example, we will be adding new elements to the beginning of the array using the unshift() method.
JavaScript
// Adding element at the beginning of an array // Declaring and initializing arrays let number_arr = [20, 30, 40]; let string_arr = [ "amit" , "sumit" ]; // unshift() // number_arr contains // [10, 20, 20, 30, 40] number_arr.unshift(10, 20); // string_arr contains // ["sunil", "anil", "amit", "sumit"] string_arr.unshift( "sunil" , "anil" ); // Printing both the array after performing unshift operation console.log( "After unshift op " ) console.log(number_arr); console.log( "After unshift op " ) console.log(string_arr); |
After unshift op [ 10, 20, 20, 30, 40 ] After unshift op [ 'sunil', 'anil', 'amit', 'sumit' ]
Method 3: JavaScript Array.pop() Method
This method is used to remove elements from the end of an array.
Syntax:
Array.pop()
Parameters: It takes no parameter
Example: In this example, we will remove an element from the end of the array using the pop() method.
JavaScript
// Removing elements from the end of an array // Declaring and initializing arrays let number_arr = [20, 30, 40, 50]; let string_arr = [ "amit" , "sumit" , "anil" ]; // pop() // number_arr contains // [ 20, 30, 40 ] number_arr.pop(); // string_arr contains // ["amit", "sumit"] string_arr.pop(); // Printing both the array after performing pop operation console.log( "After pop op " ); console.log(number_arr); console.log( "After pop op " ); console.log(string_arr); |
After pop op [ 20, 30, 40 ] After pop op [ 'amit', 'sumit' ]
Method 4: JavaScript Array.shift() Method
This method is used to remove elements from the beginning of an array
Syntax :
Array.shift()
Parameter: it takes no parameter
Example: In this example, we will remove an element from the beginning of the array using the shift() method.
JavaScript
// Removing element from the beginning of an array // Declaring and initializing arrays let number_arr = [20, 30, 40, 50, 60]; let string_arr = [ "amit" , "sumit" , "anil" , "prateek" ]; // shift() // number_arr contains // [30, 40, 50, 60]; number_arr.shift(); // string_arr contains // ["sumit", "anil", "prateek"] string_arr.shift(); // Printing both the array after performing shifts operation console.log( "After shift op " ) console.log(number_arr); console.log( "After shift op " ) console.log(string_arr); |
After shift op [ 30, 40, 50, 60 ] After shift op [ 'sumit', 'anil', 'prateek' ]
Method 5: JavaScript Array.splice() Method
This method is used for the Insertion and Removal of elements in between an Array
Syntax:
Array.splice (start, deleteCount, item 1, item 2….)
Parameters:
- Start: Location at which to perform the operation.
- deleteCount: Number of elements to be deleted, if no element is to be deleted pass 0.
- Item1, item2 …..: this is an optional parameter.
These are the elements to be inserted from the location start
Example: In this example, we will be removing an element and adding new elements at the same time using the splice() method.
JavaScript
// Removing an adding element at a particular location // in an array // Declaring and initializing arrays let number_arr = [20, 30, 40, 50, 60]; let string_arr = [ "amit" , "sumit" , "anil" , "prateek" ]; // splice() // deletes 3 elements starting from 1 // number array contains [20, 60] number_arr.splice(1, 3); // doesn't delete but inserts 3, 4, 5 // at starting location 1 number_arr.splice(1, 0, 3, 4, 5); // deletes two elements starting from index 1 // and add three elements. // It contains ["amit", "xyz", "geek 1", "geek 2", "prateek"]; string_arr.splice(1, 2, "xyz" , "geek 1" , "geek 2" ); // Printing both the array after performing splice operation console.log( "After splice op " ) console.log(number_arr); console.log( "After splice op " ) console.log(string_arr); |
After splice op [ 20, 3, 4, 5, 60 ] After splice op [ 'amit', 'xyz', 'geek 1', 'geek 2', 'prateek' ]
Method 6: JavaScript Array.slice() Method
This method returns a new array containing a portion of the original array, based on the start and end index provided as arguments
Syntax :
Array.slice (startIndex , endIndex);
Parameters :
- startIndex (optional) : An integer value representing the index at which to start extracting elements from the array. If not specified, the default value is 0, which means the slice starts at the beginning of the array.
- endIndex (optional): An integer value representing the index at which to stop extracting elements from the array (exclusive). If not specified, the default value is the length of the array, which means the slice extends to the end of the array.
Example: The following code covers all slice() method corner cases.
Javascript
const originalArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // Case 1: Extract the first 3 elements of the array const case1 = originalArr.slice(0, 3); console.log( "Case 1: Extract the first 3 elements of the array: [" + case1 + "]" ); // Case 2: Extract the last 3 elements of the array const case2 = originalArr.slice(-3); console.log( "Case 2: Extract the last 3 elements of the array: [" + case2 + "]" ); // Case 3: Extract elements from the middle of the array const case3 = originalArr.slice(3, 7); console.log( "Case 3: Extract elements from the middle of the array: [" + case3 + "]" ); // Case 4: Start index is greater than end index const case4 = originalArr.slice(5, 2); console.log( "Case 4: Start index is greater than end index: [" + case4 + "]" ); // Case 5: Negative start index const case5 = originalArr.slice(-4, 9); console.log( "Case 5: Negative start index: [" + case5 + "]" ); // Case 6: Negative end index const case6 = originalArr.slice(3, -2); console.log( "Case 6: Negative end index: [" + case6 + "]" ); // Case 7: Only start index is provided const case7 = originalArr.slice(5); console.log( "Case 7: Only start index is provided: [" + case7 + "]" ); // Case 8: Start index and end index are out of range const case8 = originalArr.slice(15, 20); console.log( "Case 8: Start index and end index are out of range: [" + case8 + "]" ); // Case 9: Start index and end index are negative and out of range const case9 = originalArr.slice(-15, -10); console.log( "Case 9: Start index and end index are negative and out of range: [" + case9 + "]" ); |
Output:
Case 1: Extract the first 3 elements of the array: [ 1,2,3]
Case 2: Extract the last 3 elements of the array: [8,9,10]
Case 3: Extract elements from the middle of the array: [4,5,6,7]
Case 4: Start index is greater than end index: []
Case 5: Negative start index: [7,8,9]
Case 6: Negative end index: [4,5,6,7,8]
Case 7: Only start index is provided: [6,7,8,9,10]
Case 8: Start index and end index are out of range: []
Case 9: Start index and end index are negative and out of range: []
Method 7: JavaScript Array some() Method
This method checks whether at least one of the elements of the array satisfies the condition checked by the argument function.
Example: Here is an example of the basic use of the Array some() method.
Javascript
// JavaScript to illustrate // lastIndexOf() method function isGreaterThan5(element, index, array) { return element > 5; } function func() { // Original array let array = [2, 5, 8, 1, 4]; // Checking for condition in array let value = array.some(isGreaterThan5); console.log(value); } func(); |
true
Method 8: JavaScript Array reduce() Method
The array reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left to right) and the return value of the function is stored in an accumulator.
Example: Here is an example of the basic use of the Array reduce() method.
Javascript
// Original array let numbers = [88, 50, 25, 10]; // Performing reduce method let sub = numbers.reduce(neveropen); function neveropen(total, num) { return total - num; } console.log(sub); |
3
Method 9: JavaScript Array map() Method
The map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method. Generally, the map() method is used to iterate over an array and call the function on every element of an array.
Example: Here is an example of the basic use of the Array map() method.
Javascript
// Original array let numbers = [4, 9, 16, 25]; // Performing map method let sub = numbers.map(neveropen); function neveropen() { return numbers.map(Math.sqrt); } console.log(sub); |
[ [ 2, 3, 4, 5 ], [ 2, 3, 4, 5 ], [ 2, 3, 4, 5 ], [ 2, 3, 4, 5 ] ]
Array Methods Summary:
Methods | Usage |
---|---|
push(element) |
Adds an element to the end of the array |
pop() |
Removes the last element of the array |
shift() |
Removes the first element of the array |
slice(beginIndex, endIndex) |
Returns a part of the array from beginIndex to endIndex |
splice(beginIndex, endIndex) |
Returns a part of the array from beginIndex to endIndex and modifies the original array by removing those elements |
concat(arr) |
Adds new elements (from arr) into the array at the end of the array |
Array.prototype[@@iterator]() |
It is not a method, but it accesses the default iterator method of an array. |
In this method, it takes an integer value (index) as a parameter and returns the element of that index |
|
In this method, it considers an array first and then copies part of an array to the same array itself and returns it, without modifying its size |
|
It returns an array of indexes and values of the given array on which the Array.entries() method is going to work. |
|
It checks whether all the elements of the array satisfy the given condition (passed by in user) or not. It returns a boolean value. |
|
This method fills a given range of array elements with the given value. This method is used to manipulate the existing array according to our needs. |
|
It is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument method. |
|
It checks all the elements of the array and whichever the first element satisfies the condition is going to print |
|
In this method, it is used to return the first index of the element in a given array that satisfies the provided testing function. |
|
This method is used to find the index of the last element in an array that matches the specified condition |
|
It is used to flatten an array, to reduce the nesting of an array. |
|
It is an inbuilt method in JavaScript that is used to flatten the input array element into a new array |
|
This method calls the provided function once for each element of the array |
|
This method returns an Array object from any object with a length property or an iterable object |
|
fromAsync(arrayLike, mapFn, thisArg) |
The fromAsync() function takes an async iterable, iterable, or array-like object as input and produces a new Array. |
This method is used to know whether a particular element is present in the array or not and accordingly, it returns true or false i.e., if the element is present, then it returns true or otherwise false. |
|
This method is used to find the index of the first occurrence of the search element provided as the argument to the method |
|
This method determines whether the value passed to this function is an array or not. This function returns true if the argument passed is an array else it returns false. |
|
This method is used to join the elements of an array into a string. The elements of the string will be separated by a specified separator and its default value is a comma(, ) |
|
The Javascript array.keys() method is used to return a new array iterator which contains the keys for each index in the given input array |
|
This method is used to find the index of the last occurrence of the search element provided as the argument to the function |
|
This method in JavaScript creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method |
|
This method is an inbuilt method in JavaScript that creates a new array instance with variables present as the argument of the method |
|
reduce( function(total, currentValue, currentIndex, arr), initialValue ) |
This method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left to right) and the return value of the function is stored in an accumulator. |
reduceRight( function(total, currentValue, currentIndex, arr), initialValue ) |
This method in JavaScript is used to convert elements of the given array from right to left to a single value |
The first element of the array becomes the last element and the last one becomes the first. It mutates the original array. |
|
This method checks whether at least one of the elements of the array satisfies the condition checked by the argument method |
|
This method is used to sort the array in place in a given order according to the compare() function |
|
It is an inbuilt function in JavaScript that is basically used to convert the elements of the given array to a string |
|
toReversed() |
It returns a new array with the elements in reversed order. |
toSorted(compareFn) |
This method is used to sort the array in place in a given order according to the compare() function and return a new array. |
toSpliced(beginIndex, endIndex) |
This method returns a new array with some elements removed or replaced at a given index. |
This method is an inbuilt function that returns the string itself. It does not modify the original string and it can be used to convert a string object to its string representation |
|
This method is used to add one or more elements to the beginning of the given array. |
|
It is an inbuilt method in JavaScript that is used to return a new array Iterator object that contains the values for each index in the array |
|
with(index, value) |
This method is used to change the value of the given index and return the new array with the replaced value. |
JavaScript provides various functions on array refer to the link below:
Note: All the above examples can be tested by typing them within the script tag of HTML or directly into the browser’s console.