15+ JavaScript Array Methods with Examples
JavaScript array methods offer powerful tools for manipulating arrays. Key methods include 'push()' and 'pop()' for adding/removing elements at the end, 'shift()' and 'unshift()' for operations at the beginning, 'map()' for creating new arrays with transformed elements, and 'filter()' for extracting elements based on conditions. Let's understand more about JavaScript Array Methods with examples.
In JavaScript, an array is a built-in data structure that includes a list of elements that store multiple elements in a single variable. A JavaScript array can be used in various ways and perform several functions thanks to JavaScript array methods.
Table of Content
- What are JavaScript Array Methods?
- Top JavaScript Array Methods
- Top JavaScript Array Methods
- Converting Arrays to Strings
- JavaScript Array Length
- JavaScript Array Reverse()
- JavaScript Array sort()
- JavaScript Array Fill()
- Javascript Array Join()
- JavaScript Array Pop()
- JavaScript Array Push()
- JavaScript Array Shift()
- Javascript Array Reduce()
- JavaScript Array unshift()
- JavaScript Array concat()
- JavaScript Array splice()
- JavaScript Array indexOf()
- JavaScript Array lastIndexOf()
- JavaScript Array find()
- JavaScript Array findIndex()
- Javascript Array filter()
- Javascript Array map()
What are JavaScript Array Methods?
JavaScript provides array methods that can be used to modify and calculate arrays. Every array method has a distinct function that executes a change or calculation to an array and saves developers from writing standard functions from scratch.
In this blog, we have shared some top JavaScript Array methods. Let’s know about them.
Want to be a certified JavaScript developer? Explore top free JavaScript certifications.
Best-suited JavaScript courses for you
Learn JavaScript with these high-rated online courses
Top JavaScript Array Methods
Converting Arrays to Strings
The JavaScript method toString() translates an array to a string of (comma-separated) array values.
const subjects = ["English", "Hindi", "Mathematics", "Physics"];document.getElementById("demo")[removed] = subjects.toString()
Output:
English, Hindi, Mathematics, Physics
JavaScript Array Length
Array length shows the number of elements in an array.
let subjects = ["English", "Hindi", "Mathematics", "Physics"];
// find the length of the subjects arraylet len = subjects.length;console.log(len);
Output:
4
JavaScript Array Reverse()
It is used to return the array in reverse order.
let subjects = [English, Hindi, Mathematics, Physics];
// reversing the subjects arraylet reversedArray = subjects.reverse();
console.log(reversedArray);
Output:
[ Physics, Mathematics, Hindi, English ]
Explore more- Top JavaScript interview questions and answers
JavaScript Array sort()
This method is used to sort the items of an array in specific order i.e, ascending or descending.
let ages = ["52", "47", "56", "64"];
// sort the ages array in ascending orderlet sortedArray = ages.sort();console.log(sortedArray);
Output:
['47', '52', '56', '64']
JavaScript Array Fill()
After filling the elements with a static value, the method returns a modified array.
// defining an array const subjects = ['English', 'Hindi', 'Mathematics'];
// filling every element of the array with 'Physics'subjects.fill("Physics");
console.log(subjects)
Output:
['Physics', 'Physics', 'Physics']
Javascript Array Join()
This method returns a new string by concatenating all the elements in an array, distinct by a specific separator.
Let message = ["All", "Is", "Well."];// join all elements of array using spacelet joinedMessage= message.join("");console.log(joinedMessage)
Output:
All Is Well.
JavaScript Array Pop()
When we use arrays, we can add and remove elements to them.
This is what the pop and push methods do.
Popping elements out of an array and pushing the elements into an array.
The pop method removes the final item from an array and then returns it.
Example:
let subjects= ["English", "Hindi", "Mathematics", "Physics"];//remove the last elementlet removedSubjects= Subjects.pop();
console.log(subjects) // ["English", "Hindi", "Mathematics"]Console.log(removedCity); //Physics
Output:
[“English”, “Hindi”, “Mathematics”]
Also read: Java vs JavaScript: Difference between Java and JavaScript.
JavaScript Array Push()
In this method, the array is expanded by one or more elements, and the new size of the array is returned.
const subjects= ["English", "Hindi", "Mathematics"];console.log(subjects.push(“Physics”)); //3console.log(subjects); // ["English", "Hindi", "Mathematics", "Physics"];
Output:
[“English”, “Hindi”, “Mathematics”, “Physics”]
JavaScript Array shift()
The shift() function eliminates first item from an array and returns the removed item. The array’s length is altered using this approach.
Example:
let subjects = ["English", "Hindi", "Mathematics", "Physics"];// removes the first element of the arraylet first = subjects.shift();console.log(first);console.log(subjects)
Output:
English ['Hindi', 'Mathematics', 'Physics']
JavaScript Array unshift()
The unshift() method integrates a new item to an array (at the starting) and “unshifts” the previous elements.
let subjects = ["English", "Hindi", "Mathematics"];
// add "Physics" at the beginning of the arraylanguages.unshift("Physics");console.log(languages)
Output:
['Physics', 'English', 'Hindi', 'Mathematics']
2 id="13"JavaScript Array concat()
The Concat() method connects two or more additional arrays that results in the creation of a new array without interrupting with the other arrays.
let studentNames = [Riya, Ram, John, Farhan]let Ages = [25, 20, 21, 23]
// join two arrays let joinedArrays = studentNames.concat(Ages);console.log(joinedArrays)
Output:
[ Riya, Ram, John, Farhan, 25, 20,21, 23 ]
JavaScript Array splice()
The splice() methods return an array by changing, adding or removing its items in place.
Example:
let colors = [Black, White, Blue, Yellow, Green, Pink];
// replace 1 element from index 4 by Redlet removedElement = colors.splice(4, 1, Red);console.log(removedElement);console.log(colors)
Output:
[ Green ] [ Black, White, Blue, Yellow, Red, Pink]
JavaScript Array indexOf()
It shows the first index value of the array or -1 if it is not available.
let subjects = ["English", "Hindi", "Mathematics", "English"];
/ Find the index of first apperance of word "English" let index = languages.indexOf("English");console.log(index)
Output:
1
JavaScript Array lastIndexOf()
A lastIndexOf() method finds the last appearance of an item in an array.
let ages = [12, 8, 13, 11, 09, 12, 07];
// searching the index of the last occurrence of 12let lastIndex = priceList.lastIndexOf(12);
console.log(lastIndex);
Output:
5
Checkout the best- JavaScript Online Courses & Certifications
JavaScript Array find()
The find() function returns the value of the first array item that fulfills the given test function.
let numbers = [1, 3, 4, 9, 8];
// function to check even numberfunction iseven(element) { return element % 2 == 0;}
// get the first even numberlet evenNumber = numbers.find(isEven);console.log(evenNumber)
Output:
4
JavaScript Array findIndex()
The index of the first number is returned by this procedure.
Example:
const array1 = [1, 6, 4, 130, 34];const isSmallestNumber = (element => element > 13);console.log(array1.findIndex(isSmallestNumber));
Output:
3
Javascript Array filter()
The filter() method creates a shallow copy of an array that is only comprised of the elements from the array that pass the test set forth by the supplied function.
const words = ['screen', 'heavy', 'less', 'past', 'rectangle', 'mouse'];
const result = words.filter(word => word.length > 4);
console.log(result);// expected output: [ 'screen', 'heavy', 'rectangle', 'mouse'
Output:
[ 'screen', 'heavy', 'rectangle', 'mouse' ]
JavaScript Array map()
The map() function returns a new array that includes the results of performing a function on each element of the original array.
Example:
let numbers = [2, 3, 4, 5, 6];
// function to return the cube of a numberfunction cube(number) { return number * number;}
// apply cube() function to each element of the numbers listlet cube_numbers = numbers.map(cube);console.log(cube_numbers);
Output:
[ 8, 27, 64, 124, 216 ]
Check out: JavaScript Functions
JavaScript Array of() Method
The array of() method forms a new Array instance based on the arguments provided.
Example:
// creating an array named vowels with elements A, E, I, O, Ulet vowels = Array.of("A", "E", "I", "0", "U");
// display contents of vowles'console.log(Vowles)
Output:
['A', 'E', 'I', '0', 'U']
JavaScript Array slice()
Slice() creates a new array object by making a shallow copy of a specific portion of an array.
let numbers = [5, 10, 15, 20, 25, 30];
// form another array by slicing numbers from index 1 to 4let newArray = numbers.slice(1,4);// console.log(newArray);[removed](newArray);
Output:
[ 10, 15, 20 ]
JavaScript Array includes()
Include() in an array contains a specified element or not.
Example:
// defining an arraylet subjects = ["English", "Hindi", "Mathematics"];
// checking whether the array contains 'Hindi'let check = subjects.includes("Hindi");
console.log(check);
Output:
true
Javascript Array reduceRight()
The reduceRight() method executes a callback function on two array values (from right to left) to reduce the array to a single value.
let numbers = [2, 4, 6, 8];
// function that adds last two values of the numbers arrayfunction sum_reducer(accumulator, currentValue) { return accumulator + currentValue;}
// returns a single value after reducing the numbers arraylet sum = numbers.reduceRight(sum_reducer);
console.log(sum);
Output:
20
Javascript Array reduce()
The reduce() method performs a reducer function on each array element and returns a single output value.
const title = ["Winners ", "Never ", "Quit."];
// function to join each string elementfunction joinStrings(accumulator, currentValue) { return accumulator + currentValue;}
// reduce join each element of the stringlet joinedString = title.reduce(joinStrings);console.log(joinedString);
Output:
Shiksha Online Blogs.
Wrapping It Up!!
We can use the JavaScript array method to write cleaner codes which ultimately makes JavaScript manipulation easier. So, use the above array methods and create more accessible codes.
Chanchal is a creative and enthusiastic content creator who enjoys writing research-driven, audience-specific and engaging content. Her curiosity for learning and exploring makes her a suitable writer for a variety ... Read Full Bio