Skip to content
Subscribe to RSS Find me on GitHub Follow me on Twitter

JavaScript Array Methods Cheat Sheet

Introduction

The JavaScript Array Methods Cheat Sheet is a comprehensive resource for developers looking to efficiently manipulate arrays in JavaScript. This cheat sheet covers the most commonly used array methods, providing developers with the knowledge they need to add or remove elements, perform filtering and mapping, and more.

With JavaScript being a popular language for web development, understanding array methods is essential for writing efficient and clean code. By mastering these methods, developers can easily manipulate arrays to suit their needs, saving time and effort.

In this cheat sheet, we will explore array manipulation methods, filtering methods, mapping methods, and searching methods. Each method will be explained in detail, providing examples of their usage to help developers grasp their functionality.

Whether you are a beginner learning JavaScript or an experienced developer looking for a quick reference, this cheat sheet is designed to be a valuable resource for all. So, let's dive in and explore the power of JavaScript array methods!

Introduction

The JavaScript Array Methods Cheat Sheet serves as a quick reference guide for developers who work with arrays in JavaScript. It covers the most commonly used array methods and provides a concise overview of their functionality. By using this cheat sheet, readers can easily manipulate arrays, add or remove elements, perform filtering and mapping operations, and more.

Arrays are a fundamental data structure in JavaScript, and knowing how to work with them efficiently is crucial for any JavaScript developer. This cheat sheet aims to simplify the learning process by providing clear explanations and code examples for each array method. Whether you are a beginner learning JavaScript or an experienced developer looking for a quick reminder, this cheat sheet will be a valuable resource for you.

Array Manipulation Methods

Array manipulation methods allow you to add or remove elements from an array. These methods are useful for modifying the contents of an array based on specific requirements.

push()

The push() method adds one or more elements to the end of an array and returns the new length of the array. It modifies the original array.

const fruits = ['apple', 'banana'];
fruits.push('orange', 'kiwi');
console.log(fruits); // Output: ['apple', 'banana', 'orange', 'kiwi']

pop()

The pop() method removes the last element from an array and returns that element. It modifies the original array.

const fruits = ['apple', 'banana', 'orange', 'kiwi'];
const removedFruit = fruits.pop();
console.log(removedFruit); // Output: 'kiwi'
console.log(fruits); // Output: ['apple', 'banana', 'orange']

unshift()

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array. It modifies the original array.

const fruits = ['apple', 'banana'];
fruits.unshift('kiwi', 'orange');
console.log(fruits); // Output: ['kiwi', 'orange', 'apple', 'banana']

shift()

The shift() method removes the first element from an array and returns that element. It modifies the original array.

const fruits = ['kiwi', 'orange', 'apple', 'banana'];
const removedFruit = fruits.shift();
console.log(removedFruit); // Output: 'kiwi'
console.log(fruits); // Output: ['orange', 'apple', 'banana']

These array manipulation methods allow you to add or remove elements from the beginning or end of an array, providing flexibility in modifying array contents.

push()

The push() method in JavaScript is used to add one or more elements to the end of an array. This is a commonly used method for appending new elements to an existing array.

Here is an example of how to use the push() method:

let fruits = ['apple', 'banana'];
fruits.push('orange', 'grape');
console.log(fruits);

In this example, we have an array called fruits that initially contains two elements: 'apple' and 'banana'. We then use the push() method to add two more elements, 'orange' and 'grape', to the end of the array. The output of the console.log() statement will be ['apple', 'banana', 'orange', 'grape'].

The push() method can also be used to add a single element to an array. For example:

let numbers = [1, 2, 3];
numbers.push(4);
console.log(numbers);

In this case, the push() method is used to add the number 4 to the end of the numbers array. The output will be [1, 2, 3, 4].

It is important to note that the push() method modifies the original array and returns the new length of the array after the elements have been added.

pop()

The pop() method is used to remove the last element from an array and returns that element. It modifies the original array by removing the element from the end.

Here is an example of how to use the pop() method:

const fruits = ["apple", "banana", "orange"];

const removedFruit = fruits.pop();

console.log(removedFruit); // Output: "orange"
console.log(fruits); // Output: ["apple", "banana"]

In this example, the pop() method is called on the fruits array. The last element, "orange", is removed from the array and stored in the removedFruit variable. The removedFruit variable is then printed to the console, which outputs "orange". Finally, the fruits array is printed to the console, which now contains only the elements "apple" and "banana".

The pop() method is commonly used when you need to remove the last element from an array, such as when implementing a stack data structure or when dynamically managing a list of items.

unshift()

The unshift() method is used to add one or more elements to the beginning of an array. It modifies the original array and returns the new length of the array.

Here's an example that demonstrates how to use unshift():

const fruits = ['apple', 'banana', 'orange'];

fruits.unshift('pear', 'grape');

console.log(fruits);
// Output: ['pear', 'grape', 'apple', 'banana', 'orange']

In the example above, the unshift() method adds the elements 'pear' and 'grape' to the beginning of the fruits array. The resulting array is ['pear', 'grape', 'apple', 'banana', 'orange'].

The unshift() method can also be used to add a single element to the beginning of the array. For example:

const numbers = [2, 3, 4];

numbers.unshift(1);

console.log(numbers);
// Output: [1, 2, 3, 4]

In this case, the unshift() method adds the number 1 to the beginning of the numbers array, resulting in [1, 2, 3, 4].

shift()

The shift() method is used to remove the first element from an array and returns the removed element. This method modifies the original array.

Here is an example of how shift() can be used:

let fruits = ["apple", "banana", "orange"];

let removedFruit = fruits.shift();

console.log(removedFruit); // Output: "apple"
console.log(fruits); // Output: ["banana", "orange"]

In the example above, the shift() method is called on the fruits array. The first element, "apple", is removed and stored in the removedFruit variable. The fruits array is then modified and contains only the remaining elements, "banana" and "orange".

The shift() method is useful when you want to remove and retrieve the first element of an array. It can be used in various scenarios, such as processing a queue or removing items from a to-do list.

Array Filtering Methods

Array filtering methods in JavaScript allow you to create new arrays based on certain conditions. These methods are useful when you want to extract specific elements from an array that meet a certain criteria. In this section, we will explore three commonly used array filtering methods: filter(), some(), and every().

filter()

The filter() method creates a new array with all elements that pass a provided test. It takes in a callback function as an argument, which is executed for each element in the array. The callback function should return either true or false, indicating whether the current element should be included in the new array.

Here's an example that filters out all the even numbers from an array:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const evenNumbers = numbers.filter((number) => number % 2 === 0);

console.log(evenNumbers); // Output: [2, 4, 6, 8, 10]

In the code snippet above, the filter() method is used to create a new array called evenNumbers that only contains the even numbers from the numbers array.

some()

The some() method tests whether at least one element in the array passes a provided test. It also takes in a callback function as an argument, which is executed for each element in the array. The callback function should return either true or false, indicating whether the current element passes the test.

Here's an example that checks if the array contains any number greater than 10:

const numbers = [5, 8, 12, 3, 9];

const hasNumberGreaterThan10 = numbers.some((number) => number > 10);

console.log(hasNumberGreaterThan10); // Output: true

In the code snippet above, the some() method returns true because the array contains the number 12, which is greater than 10.

every()

The every() method tests whether all elements in the array pass a provided test. It also takes in a callback function as an argument, which is executed for each element in the array. The callback function should return either true or false, indicating whether the current element passes the test.

Here's an example that checks if all the numbers in the array are positive:

const numbers = [1, 2, 3, 4, 5];

const areAllPositive = numbers.every((number) => number > 0);

console.log(areAllPositive); // Output: true

In the code snippet above, the every() method returns true because all the numbers in the array are greater than 0.

These array filtering methods are powerful tools for manipulating and extracting specific elements from arrays based on certain conditions. They can greatly simplify your code and make it more readable.

Remember to refer to this cheat sheet whenever you need to use array filtering methods in your JavaScript projects.

filter()

The filter() method in JavaScript creates a new array with all elements that pass a provided test. It takes in a callback function as an argument, which is executed on each element of the array. The callback function should return true or false to indicate whether the element should be included in the filtered array.

Here's an example that demonstrates the usage of filter():

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const evenNumbers = numbers.filter((number) => {
  return number % 2 === 0;
});

console.log(evenNumbers); // Output: [2, 4, 6, 8, 10]

In the example above, we have an array of numbers. The filter() method is called on the array, and a callback function is provided. This callback function checks if each number in the array is even by using the modulo operator % to check if the remainder is 0 when divided by 2. If the condition is true, the number is included in the new array evenNumbers.

The filter() method is commonly used when you need to extract specific elements from an array based on some condition. It allows you to create a new array without modifying the original array.

some()

The some() method in JavaScript tests whether at least one element in the array passes a provided test. It returns a boolean value, true if any element passes the test, and false otherwise. This method is useful when you need to check if any element in the array satisfies a certain condition.

Here is an example that demonstrates the usage of some():

const numbers = [1, 2, 3, 4, 5];

const hasEvenNumber = numbers.some((number) => {
  return number % 2 === 0;
});

console.log(hasEvenNumber); // Output: true

In the above example, we have an array of numbers. We use the some() method to check if any of the numbers in the array is even. The callback function passed to some() checks if the number is divisible by 2 (i.e., an even number). Since the array contains the number 2, which is divisible by 2, the some() method returns true.

The some() method can be particularly useful when you want to quickly determine if any element in an array satisfies a specific condition without having to iterate over the entire array manually.

every()

The every() method tests whether all elements in the array pass a provided test. It returns a boolean value indicating whether all elements satisfy the condition.

Here's an example that uses every() to check if all numbers in an array are even:

const numbers = [2, 4, 6, 8, 10];
const allEven = numbers.every((number) => number % 2 === 0);

console.log(allEven); // Output: true

In the code example above, the every() method is called on the numbers array. The provided test checks if each number in the array is divisible by 2 with no remainder. Since all numbers in the array are even, the every() method returns true and assigns it to the allEven variable.

The every() method can also be used with other conditions or tests based on the specific requirements of your code.

Array Mapping Methods

In JavaScript, array mapping methods allow us to create a new array by manipulating each element in an existing array. These methods are particularly useful when we need to transform data or perform calculations on each element.

map()

The map() method creates a new array with the results of calling a provided function on every element in the original array. It takes a callback function as an argument, which is executed for each element in the array. The callback function can perform any transformation or calculation on the element and returns the modified value.

Here's an example that uses the map() method to double each element in an array:

const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map((number) => number * 2);

console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]

In the example above, the map() method is called on the numbers array, and the callback function (number) => number * 2 multiplies each element by 2. The resulting array doubledNumbers contains the modified values.

forEach()

The forEach() method allows us to execute a provided function once for each element in an array. It does not create a new array, but it is often used for performing an action on each element.

Here's an example that uses the forEach() method to log each element in an array:

const fruits = ['apple', 'banana', 'orange'];

fruits.forEach((fruit) => {
  console.log(fruit);
});

// Output:
// apple
// banana
// orange

In the example above, the forEach() method is called on the fruits array, and the provided callback function logs each element to the console.

reduce()

The reduce() method applies a function against an accumulator and each element in the array to reduce it to a single value. It takes a callback function as an argument, which is executed for each element in the array. The callback function takes two parameters: the accumulator and the current element. The accumulator is the value that is returned and passed as the first argument of the callback function for each subsequent iteration.

Here's an example that uses the reduce() method to calculate the sum of all elements in an array:

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, number) => accumulator + number, 0);

console.log(sum); // Output: 15

In the example above, the reduce() method is called on the numbers array. The callback function (accumulator, number) => accumulator + number adds each element to the accumulator, starting from an initial value of 0. The final result is stored in the sum variable.

These array mapping methods provide powerful tools for manipulating and transforming array data. By understanding how to use map(), forEach(), and reduce(), developers can efficiently process and modify array elements according to their requirements.

map()

The map() method in JavaScript creates a new array by applying a provided function to every element in the original array. It is commonly used to transform or manipulate the elements of an array.

Here's an example that demonstrates the usage of map():

const numbers = [1, 2, 3, 4, 5];

const doubledNumbers = numbers.map((num) => num * 2);

console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]

In the example above, we have an array called numbers that contains the numbers 1 to 5. By using map(), we apply a function that multiplies each number by 2. The resulting array, doubledNumbers, will contain the elements [2, 4, 6, 8, 10].

The map() method is especially useful when you want to transform each element of an array without modifying the original array. It allows you to perform complex operations on each element and return a new array with the transformed values.

forEach()

The forEach() method is used to execute a provided function once for each element in an array. It is a simple and convenient way to perform an action on each element of an array without the need for explicit looping.

Here is an example of how forEach() can be used:

const numbers = [1, 2, 3, 4, 5];

numbers.forEach(function(number) {
  console.log(number * 2);
});

In this example, the forEach() method is called on the numbers array. The provided function takes an argument number, which represents each element of the array. Within the function, we multiply each number by 2 and log the result to the console.

The output of this code will be:

2
4
6
8
10

The forEach() method is particularly useful when we want to iterate over an array and perform an action on each element. It eliminates the need for a separate loop construct and makes the code more concise and readable.

reduce()

The reduce() method in JavaScript applies a function against an accumulator and each element in the array to reduce it to a single value. It takes in two parameters: the reducer function and an optional initial value for the accumulator.

The reducer function takes in four parameters: the accumulator, the current value, the current index, and the array itself. It performs some operation on the accumulator using the current value and returns the updated accumulator. This process is repeated for each element in the array until a single value is obtained.

Here is an example that demonstrates the usage of reduce():

const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);

console.log(sum); // Output: 15

In the above example, the reduce() method is used to calculate the sum of all the numbers in the array. The initial value of the accumulator is set to 0. The reducer function adds the current value to the accumulator in each iteration, and the final result is 15.

The reduce() method is powerful and can be used for various operations such as finding the maximum or minimum value in an array, concatenating strings, or calculating averages. It provides a flexible way to perform calculations on array elements and obtain a single value as the result.

Array Searching Methods

Searching for specific elements or values in an array is a common task in JavaScript development. The following array methods provide convenient ways to search for elements in an array.

indexOf()

The indexOf() method returns the first index at which a given element can be found in an array. It searches the array from the beginning and stops as soon as it finds a match. If the element is not found, it returns -1.

Here's an example of using indexOf():

const fruits = ['apple', 'banana', 'orange', 'kiwi'];

console.log(fruits.indexOf('banana')); // Output: 1
console.log(fruits.indexOf('grape')); // Output: -1

includes()

The includes() method determines whether an array contains a certain element. It returns true if the element is found in the array, and false otherwise.

Here's an example of using includes():

const fruits = ['apple', 'banana', 'orange', 'kiwi'];

console.log(fruits.includes('banana')); // Output: true
console.log(fruits.includes('grape')); // Output: false

find()

The find() method returns the first element in the array that satisfies a provided testing function. It stops searching as soon as it finds a matching element and returns that element. If no element satisfies the testing function, it returns undefined.

Here's an example of using find():

const numbers = [1, 2, 3, 4, 5];

const foundNumber = numbers.find((number) => number > 3);

console.log(foundNumber); // Output: 4

These array searching methods provide powerful ways to find specific elements or values in an array. Whether you need to locate the index of an element, check if an element exists, or find the first element that satisfies a condition, these methods have got you covered.

indexOf()

The indexOf() method in JavaScript returns the first index at which a given element can be found in an array. If the element is not present in the array, it returns -1. This method is useful when you want to check if a specific element exists in an array and find its position.

Here is an example that demonstrates the usage of indexOf():

const fruits = ['apple', 'banana', 'orange', 'mango'];

console.log(fruits.indexOf('banana')); // Output: 1
console.log(fruits.indexOf('watermelon')); // Output: -1

In the above example, we have an array called fruits which contains different fruit names. We use the indexOf() method to find the index of the element 'banana' in the array, which returns 1 as the output. Similarly, when we search for 'watermelon' which is not present in the array, the indexOf() method returns -1.

The indexOf() method can also take an optional second parameter, which specifies the starting index from where the search should begin. For example:

console.log(fruits.indexOf('orange', 2)); // Output: 2

In this case, the indexOf() method starts searching for the element 'orange' from index 2 onwards in the array fruits. As 'orange' is present at index 2, the method returns 2 as the output.

Overall, the indexOf() method is a handy tool for finding the position of an element in an array, allowing you to perform further operations based on its presence or absence.

includes()

The includes() method is used to determine whether an array contains a certain element. It returns a boolean value, true if the element is found in the array, and false otherwise.

Here's an example to illustrate its usage:

const fruits = ['apple', 'banana', 'orange'];

console.log(fruits.includes('banana')); // Output: true
console.log(fruits.includes('grape')); // Output: false

In the example above, we have an array called fruits that contains three elements: 'apple', 'banana', and 'orange'. We use the includes() method to check if the array contains the element 'banana'. Since 'banana' is present in the array, the first console.log() statement returns true. On the other hand, when we check if the array includes the element 'grape', the includes() method returns false because 'grape' is not found in the array.

The includes() method is useful when you want to quickly check if an array contains a specific value without having to manually iterate through the array.

find()

The find() method in JavaScript returns the first element in an array that satisfies a provided testing function. It is useful when you want to search for a specific element in an array based on a condition.

Here is an example of how find() can be used:

const numbers = [1, 2, 3, 4, 5];

const foundElement = numbers.find((element) => element > 3);

console.log(foundElement);

In this example, the find() method is used to search for the first element in the numbers array that is greater than 3. The arrow function (element) => element > 3 is the testing function that defines the condition. The find() method returns the value 4, as it is the first element that satisfies the condition.

It's important to note that find() only returns the first matching element. If no element satisfies the condition, find() returns undefined.

The find() method is commonly used when you want to retrieve a specific object from an array based on a certain property value. By defining a testing function that checks for the desired property value, you can easily locate and retrieve the desired object.

It's worth mentioning that find() stops iterating over the array as soon as it finds the first matching element. This makes find() more efficient than other methods like filter() when you only need to find a single element.

Conclusion

In conclusion, understanding and familiarizing yourself with the various array methods in JavaScript is crucial for efficient and effective development. These methods provide powerful tools for manipulating, filtering, mapping, and searching arrays, allowing you to easily perform complex operations on your data.

By using array methods such as push(), filter(), map(), and indexOf(), you can streamline your code and achieve desired results with less effort. These methods not only make your code more readable and maintainable, but they also improve the performance of your applications.

As you continue to work on JavaScript projects, it is highly recommended to refer to this cheat sheet whenever you need to perform operations on arrays. It will serve as a handy reference, saving you time and effort by providing quick access to the syntax and usage of each array method.

Remember, mastering array methods will make you a more efficient and productive JavaScript developer, enabling you to build robust and scalable applications. So, keep exploring, practicing, and utilizing these array methods to take your JavaScript skills to the next level.