Hi, Developers! you are most welcome to the series of Cheat Sheet, in this series we shared the article on JavaScript String Method Cheat Sheet, and now I am sharing the Comprehensive Guide on JavaScript Array Methods Cheat Sheets.
JavaScript, is a most popular programming language, which has a lot of array methods that allow developers to manipulate and transform arrays efficiently.
Understanding and mastering these array methods can greatly enhance your ability to work with Arrays in JavaScript.
In this article, we will provide you with a comprehensive cheat sheet of JavaScript array methods, covering their syntax, functionality, Examples, and common use cases of each and every methods.
Whether you’re a beginner or an experienced developer, this cheat sheet will serve as a handy reference to help you leverage the power of arrays in your JavaScript projects.
What is Array in JavaScript?
In JavaScript, an array is a data structure used to store multiple elements in a single variable. It is a fundamental feature of the language and provides a convenient way to work with collections of data.
An array in JavaScript is an ordered list of elements, where each element can be of any data type, including numbers, strings, objects, or even other arrays. The elements in an array are accessed using their index, starting from 0 for the first element.
Arrays in JavaScript are dynamic, meaning that their size can change dynamically during runtime. You can add or remove elements from an array, modify existing elements, or perform various operations on the array as a whole.
To create an array in JavaScript, you can use array literals by enclosing the elements in square brackets [ ], or by using the Array constructor.
// Array literal const numbers = [1, 2, 3, 4, 5]; // Using Array constructor const fruits = new Array('apple', 'banana', 'orange');
Arrays offer a wide range of methods and properties that allow you to manipulate, iterate, search, filter, and transform array elements efficiently.
This article is dedicated to the JavaScript Array Methods Cheat Sheet so let’s dive into the world of Array Methods.
JavaScript Array Methods Cheat Sheet
JavaScript offers lots of Array Methods. To effectively work with arrays, developers need a solid understanding of the various array methods available in JavaScript.
This comprehensive cheat sheet serves as a valuable reference for mastering JavaScript array methods, empowering developers to efficiently perform operations like adding, removing, searching, filtering, and transforming array elements.
Here is the list of Array Methods with their short description and examples.
Accessing Array Elements:
JavaScript Array has a lot of methods for accessing the element from the array.
1. Array.indexOf() method:
Array.indexOf() allows us to find the first index for the specified element if the element is present in the array, otherwise, it returns -1. It always starts the search from the beginning of the Array.
// Example-1 let fruits = ["apple", "banana", "mango"]; // finding element in the array console.log(fruits.indexOf("apple")); // Output : 0 console.log(fruits.indexOf("grapes")); // Output : -1 (not found)
2. Array.lastIndexOf() method:
Array.lastIndexOf() method is the exact opposite of indexOf(). It allows us to find the last index for the specified element if present, otherwise, it returns -1. It always starts searching backward from the end of the Array.
// Example-1 let fruits = ["apple", "banana", "mango"]; console.log(fruits.indexOf("mango")); // Output : 1 console.log(fruits.indexOf("grapes")); // Output : -1 (not found) // Example-2 let numbers = [1,2,3,4,5]; console.log(numbers.indexOf(4)); // Output : 3 console.log(numbers.indexOf(6)); // Output : -1 (not found)
3. Array.includes() method:
Array.includes() returns true if the specified element is present in the array at any index, otherwise, it returns false. Remember it never returns the index number and nor returns -1.
// Example-1 let fruits = ["apple", "banana", "mango"]; console.log(fruits.includes("mango")); // Output : true console.log(fruits.includes("grapes")); // Output : false (not found) // Example-2 let numbers = [1,2,3,4,5]; console.log(numbers.includes(4)); // Output : true console.log(numbers.includes(6)); // Output : -1 (not found)
Modifying Arrays:
JavaScript offers a bunch of array methods that help to modify the array element they are as follows.
1. Array.push() method:
Array.push() is the most popular array method that allows to push or add an element at the end of the array. It returns the updated length of the array.
Using this method you can add multiple elements at a time, for multiple elements use comma-separated elements.
// Example-1 let fruits = ["apple", "banana"]; fruits.push("mango"); // Added to end of the array console.lor(fruits); // Output : ["apple", "banana", "mango"] // Example-2 let numbers = [1,2,3,4,5]; numbers.push(6, 7, 8); // Added 6 at end of the array console.log(numbers); // Output : [1,2,3,4,5,6,7,8]
2. Array.pop() method:
Array.pop() is used to remove or pop out the last element from the array and it returns the removed or poped element.
// Example-1 let fruits = ["apple", "banana"]; let removedFruit = fruits.pop(); console.log(removedFruit); // Output : banana; console.log(fruits); // Output : ["apple"] // Example-2 let numbers = [1,2,3,4,5]; let removedNumber = numbers.pop(); console.log(removedNumber); // Output : 5 console.log(numbers); // Output : [1,2,3,4]
3. Array.shift() method:
Array.shift() is similar to the pop method pop removes the element from the end of the array but shift removes the element from the beginning of the array. Basically, it removes the first element and returns the removed element.
// Example-1 let fruits = ["apple", "banana"]; let removedFruit = fruits.shift(); console.log(removedFruit); // Output : apple; console.log(fruits); // Output : ["banana"] // Example-2 let numbers = [1,2,3,4,5]; let removedNumber = numbers.shift(); console.log(removedNumber); // Output : 1 console.log(numbers); // Output : [2,3,4,5]
4. Array.unshift() method:
Array.unshift() method adds one or multiple elements at the beginning of the array and returns the new length of the array. It mutates the original array.
// Example let numbers = [1,2,3,4]; const newLength = array.unshift(0); // Added 0 to the beginning of the array console.log(numbers); // Output : [0,1,2,3,4] console.log(newLength); // Output : 5
5. Array.splice() method:
The Array.splice() method is used to modify the array element by adding or removing elements from it. It allows you to add or remove the elements at the specified position. splice() method returns the removed element.
// Example let fruits = ['apple', 'banana', 'orange', 'grape']; // Remove 'banana' from the array let removedFruit = fruits.splice(1, 1); // Starting from index 1, remove 1 element console.log(fruits); // Output: ['apple', 'orange', 'grape'] console.log(removedFruit); // Output: ['banana'] // Insert 'kiwi' and 'peach' into the array at index 2 fruits.splice(2, 0, 'kiwi', 'peach'); console.log(fruits); // Output: ['apple', 'orange', 'kiwi', 'peach', 'grape']
6. Array.fill() method:
Array.fill() method allows to fill all the elements of an array with a static value. It modifies the original array and also returns the modified array. The method tasks up to three arguments
- The element to use for filling the array.
- An optional start index indicating where to start filling the array (default is 0).
- An optional end index indicating where to stop filling the array (default is the length of the array).
If the start index (that is the second argument) is negative, it is treated as array.length + start index. Similarly, if the end index (that is the third argument) is negative, it is treated as array.length + end index.
// Example // Creating the array with null element let array = [null, null, null, null, null]; // Filling the array with a static value 0 array.fill(0); console.log(array); // Output: [0, 0, 0, 0, 0] // Filling a specific range of the array with a value '1' array.fill(1, 1, 4); // Starting from index 1 to index 3 (exclusive) console.log(array); // Output: [0, 1, 1, 1, 0] // Filling the entire array with a value '2' using negative start and end index array.fill(2, -5, -1); // Equivalent to array.fill(2, 0, 4) console.log(array); // Output: [2, 2, 2, 2, 0]
Iterating over Arrays:
Iterating over the array is a common task in JavaScript. There are a lot of array methods that help to iterate the elements from an array they are as follows.
1. Array.map() method:
The Array.map() method helps to transform each item in an array and return a new transformed array. Remember one thing it doesn’t transform the original array.
It tasks a callback function as an argument which allows writing the transformation code for each item of the array.
// Example-1 const fruits = ['apple', 'banana', 'orange', 'grape']; // Capitalizing the all letter of each fruit const capitalizedFruits = fruits.map(function(fruit) {return fruit.toUpperCase()}); console.log(capitalizedFruits); // Output: ['APPLE', 'BANANA', 'ORANGE', 'GRAPE'] // Example-2 const numbers = [1, 2, 3, 4, 5]; // Doubling each number in the array const doubledNumbers = numbers.map(function(num) {return num * 2}); console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
2. Array.forEach() method:
Array.forEach() is the most useful method in JavaScript which allows to iteration of the array element in ascending order. It doesn’t create a new array.
// Example const numbers = [1, 2, 3, 4, 5]; numbers.forEach(function(number) { console.log(number); });
3. Array.reduce() method:
The array.reduce() method is used to combine its element into a single value, like adding all elements, finding the maximum, or combining them in some other ways.
It executes a reducer function on each element and it takes two arguments an accumulator and the current value and returns the accumulated result.
// Example let numbers = [1, 2, 3, 4, 5]; let sum = numbers.reduce(function(acc, crr) { return acc + crr; },0); console.log(sum); // Output: 15
4. Array.every() method:
The Array.every() method is used to test every element present in the array against a specified condition. It returns true if all elements pass the given test condition; otherwise, it returns false.
// Example let numbers = [2, 4, 6, 8]; let isAllEven = numbers.every(function(num) { return num % 2 === 0 }); console.log(isAllEven); // Output: true
5. Array.some() method:
Array.some() method is used to test if at least one element present in the array satisfies the specified condition. It returns true if an element passes the test; otherwise, it returns false.
// Example let numbers = [2, 4, 6, 8, 9, 10]; let hasOddNumber = numbers.some(function(num) { return num % 2 !== 0; }); console.log(hasOddNumber); // Output: true
Searching and Filtering Arrays:
JavaScript offers several methods to search for specific values based on certain conditions. Some methods are given below.
1. Array.find() method:
Array.find() method is used to find the first matched element that passes the given condition. It returns the first matching element or undefined if the element is not found.
It takes a callback function as an argument that allows writing the condition for the element.
// Example let numbers = [10, 20, 30, 40, 50]; let foundNumber = numbers.find(functio(num) { return num > 25); console.log(foundNumber); // Output: 30
1. Array.findIndex() method:
Array.findIndex() method is used to find the first matched element’s index number that passes the given condition. It returns the index number of the first matching element or -1 if the element is not found.
It also takes a callback function as an argument that allows writing the condition for the element.
// Example let numbers = [10, 20, 30, 40, 50]; let foundIndex = numbers.find(function(num) { return num > 25}); console.log(foundIndex); // Output: 2
3. Array.filter() method:
Basically Array.filter() method is used to filter the element in the array and create a new array with filtered element. It takes a callback method as an argument that returns true to include an element and false to exclude an element.
// Example const numbers = [1, 2, 3, 4, 5]; const evenNumbers = numbers.filter(function(num) { return num % 2 === 0; }); console.log(evenNumbers); // Output: [2, 4]
Array Comparison and Combination:
Comparing and combining arrays is another common requirement in JavaScript. We’ll cover methods such as concat, join, and isArray to compare arrays,
1. Array.concat() method:
Array.concat() method is used to concatenate two or more arrays into a single array. It creates a new array that contains all the elements of the original array and the other array elements are passed as arguments, without modifying the original array.
// Example let array1 = [1, 2, 3]; let array2 = [4, 5, 6]; let array3 = [7, 8, 9]; let newArray = array1.concat(array2, array3); console.log(newArray); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
2. Array.join() method:
If you want to convert an array into a string with some separator between the elements, then Array.join() method is useful.
// Example let fruits = ["apple", "banana", "orange"]; // Joining array elements with a comma and a space let result = fruits.join(", "); console.log(result); // Output: "apple, banana, orange"
3. Array.isArray() method:
Array.isArray() method in JavaScript is used to check whether a given value is an array, it returns true if it is, otherwise, it returns false.
// Example const array = [1, 2, 3]; const obj = { name : "Bikash" } console.log(Array.isArray(array)); // Output: true console.log(Array.isArray(obj)); // Output: false
Additional Array Operations:
Apart from the above methods, Array has some additional methods which are discussed in this section.
1. Array.reverse() method:
Array.reverse() method in JavaScript reverses the order of elements in an array in place, mutates the original array, and returns the reversed array.
// Example const numbers = [1, 2, 3, 4, 5]; numbers.reverse(); console.log(numbers); // Output: [5, 4, 3, 2, 1]
2. Array.toString() method:
Array.toString() is used to convert all elements of the array into a string, each element is separated with a comma and it returns the converted string.
// Example const array = [1, 2, 3, 4, 5]; const arrayAsString = array.toString(); console.log(arrayAsString); // Output: "1,2,3,4,5"
Summary and Conclusion
In the JavaScript Array Methods Cheat Sheet article, we covered lots of array methods that help to create, manipulate, search, filter, and transform the arrays.
We covered methods like indexOf, lastIndexOf, includes, push, pop, shift, unshift, splice, fill, map, forEach, reduce, every, some, find, findIndex, filter, concat, join, isArray, reverse, and toString method that helps you to understand array in depth. By mastering these methods, you will be able to write more concise, efficient, and maintainable code.
I hope you have enjoyed this article if yes, you must share it with your college friends and your junior.
Thank you so much;
JavaScript Array Methods Cheat Sheet FAQs
1. What is a JavaScript array?
An array in JavaScript is a linear data structure that stores a collection of elements, where each element can be accessed by its index.
2. What are some commonly used array methods in JavaScript?
Some commonly used JavaScript array methods are push(), pop(), shift(), unshift(), slice(), splice(), forEach(), map(), filter(), reduce(), every(), some(), concat(), join(), reverse(), toString(), and toLocaleString().
3. Can I chain multiple array methods together?
Yes, you can chain multiple array methods together in JavaScript to perform complex operations on arrays. This is known as method chaining and allows you to write concise and readable code.
4. Are array methods mutable or immutable?
Most array methods in JavaScript are mutable, meaning they modify the original array. However, some methods, such as slice() and concat(), return a new array without modifying the original.
5. How can I remember all the array methods and their syntax?
Practice and repetition are key to remembering array methods and their syntax. You can also refer to cheat sheets, documentation, and tutorials as needed to reinforce your understanding.