JavaScript Array Methods Cheat Sheet

Introduction

JavaScript is a versatile and powerful programming language that is widely used for creating dynamic and interactive web applications. One of the key features of JavaScript is its built-in support for arrays, which are data structures used to store and manipulate collections of elements. JavaScript provides a rich set of array methods that allow developers to perform various operations on arrays efficiently. Array methods in JavaScript enable developers to add, remove, modify, and search for elements within an array. These methods provide a convenient and concise way to perform complex operations without having to write extensive loops or conditional statements. By leveraging array methods, developers can write cleaner, more readable code and improve the overall efficiency of their programs.

Why we used it?

Array methods in JavaScript are used for various purposes to manipulate, transform, and work with arrays more efficiently. Here are some reasons why we use array methods in JavaScript -

Adding and Removing Elements: Array methods such as push(), pop(), shift(), and unshift() allow us to add or remove elements from an array easily. These methods help us manage the size and content of an array dynamically.

Iterating over Arrays: Array methods like forEach(), map(), filter(), and reduce() provide convenient ways to iterate over array elements and perform operations on each element or the entire Array. These methods help us avoid writing manual loops and make our code more concise and readable.

Transforming Arrays: Array methods like map() and filter() enable us to transform arrays by applying specific operations or conditions to each element. For example, we can use map() to modify or alter each element of an array based on a provided function or filter() to create a new array with only the elements that meet a given condition.

Searching and Accessing Elements: Array methods like find() and indexOf() help us search for specific elements within an array. They allow us to locate elements based on a provided condition or retrieve their index positions.

Slicing and Concatenating Arrays: Array methods such as slice() and concat() enable us to extract a subset of elements from an array or merge multiple arrays, respectively. These methods provide flexibility in manipulating array contents and creating new arrays.

Sorting and Reversing Arrays: Array methods like sort() and reverse() allow us to sort an array's elements in ascending or descending order and reverse the order of elements within an array.

Manipulating Array Content: Array methods such as splice() allow us to modify the content of an array by adding, removing, or replacing elements at specific positions.

What is Array?

Data must be kept in a variable when programming. A variable is nothing more than the name of the memory location where the data is stored. Considering that one variable may hold one piece of data at a time in memory, storing identical sorts of data will necessitate storing each piece of data in a separate variable. Given the volume of data and variables, it is hard to name each variable uniquely in this situation. Here, array data structures are used to address this issue. The Array is a variable that can hold numerous pieces of data at once under a single array name. The Array can therefore hold various data, and we don't need to use different variable names.

Declaration of Array in Javascript

This array data structure is used by almost all computer languages to efficiently store and access data. There are two ways to write an array in Javascript.

Using the [] bracket

It's very easy to declare an array using the [] bracket. At first, you have to declare the array name and then assign the entire Array. For example,

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

We currently have 9 elements or pieces of data stored under the arrayName. There are nine possible variable names to write down if variables are used in place of the Array. But under a single name, the Array can be solved.

Using new Array()

In this method, a new Array() must be written in place of a [] bracket. For instance,

const arr = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9);

It is normal practice to declare an array using the [] bracket. Let's now examine how an array is graphically represented and how to retrieve its contents, among other things.

1. values() Method

The iterator that this method returns contains values for each index in the Array. Arguments are unnecessary. The values() method is also a built-in method that returns an iterator of the values for each element in an array. This method is called on an array object and does not take any arguments.

Syntex

arrayName.values();

Example

const arr = ['apple','banana','cherry']
const iterator = arr.values();

  for(const value of iterator)
  {
    console.log(value);   //Output apple banana cherry
  }

In this example, we create an array array with three elements. We then call the values() method on the array object and assign the returned iterator to array values. We then use a for loop to iterate through the values array values individually and log each value to the console. The output shows that we successfully iterated through the values of arr.

2. length() Method

Returns the number of elements in an array. The length is a built-in property of an array that returns the number of elements in the Array. It is a numeric value that represents the length or size of the Array.

Syntax

arrayName.length();

Example

const myArray = [1, 2, 3, 4, 5];
console.log(myArray.length);

// Output: 5

In this example, we create an array myArray with five elements and then use the length property to get the number of elements. The output myArray.length is 5, which is the number of elements in the Array. The length property is useful when you need to know the number of elements in an array, for example, in a loop where you must iterate through all the elements in an array.

3. reverse() Method

 Reverses the order of elements in an array.reverse() is a built-in method that reverses the order of elements in an array. This method operates directly on the Array and does not create a new array. It modifies the original Array and returns a reference to the reversed Array.

Syntax

arrayName.reverse();

Example

const myArray = [1, 2, 3, 4, 5];
console.log(myArray);

myArray.reverse();
console.log(myArray);

// Output:
// [1, 2, 3, 4, 5]
// [5, 4, 3, 2, 1]

In this example, we first create an array myArray with five elements and log it to the console. We then call the reverse() method on myArray, which reverses the order of elements in the Array. Finally, we log the reverse myArray to the console, which shows the elements in reverse order. The reverse() method is useful when you need to reverse the order of elements in an array. For example, when you need to display elements in a list in reverse order or when you need to process elements in an array from the end to the beginning.

4. sort() Method

Sorts the elements of an array in ascending or specified order. The sort() is a built-in method that is used to sort the elements of an array in ascending order. The sort() method sorts the elements of an array in place and returns a reference to the sorted Array.

Syntax

arrayName.sort(compareFunction);

Example

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

fruits.sort();
console.log(fruits);

// Output:
// ["banana", "apple", "orange", "grape"]
// ["apple", "banana", "grape", "orange"]

In this example, we first create an array of fruits with four elements and log it to the console. Then we call the sort method on the fruits array, which sorts the elements of the Array in ascending order. Finally, we log the sorted fruits array to the console, which shows the elements in sorted order. The sort() method also accepts an optional argument that can be used to specify the order of sorting. This optional argument can be a compare function that takes two arguments (the elements to be compared) and returns a negative, zero, or positive value. If the compare function returns a negative value, the first element is sorted before the second element. If the compare function returns a positive value, the second element is sorted before the first element. If the compare function returns zero, no sorting occurs between the two elements.

5. at() Method

This method is not a standard JavaScript array method. The at() method is not a standard JavaScript array method, but it is available in some JavaScript libraries and frameworks, such as Lodash. The at() method is used to retrieve one or more elements from an array based on their index. It accepts one or more index parameters and returns an array of elements at those indices. If an index is out of range or negative, undefined is returned at that index.

Syntax

arrayName.length();

Example

const myArray = [1, 2, 3, 4, 5];
console.log(_.at(myArray, 0, 2, 4));

// Output: [1, 3, 5]

In this example, we first create an array myArray with five elements and log it to the console. Then we use the at the () method from Lodash to retrieve the elements at the first, third, and fifth index of the myArray. The result is an array of elements [1, 3, 5]. It's important to note that the at() method is not a standard array method in JavaScript, and it's not widely used. While it can be useful in some specific cases, it may not be the best choice for general-purpose array manipulation.

6. fill() Method

Changes all elements in an array with a static value from a start index to an end index.fill() is a built-in method used to change the values of all elements in an array with a static value from a start index to an end index. This method modifies the original Array and also returns a reference to the modified Array.

Syntax

arrayName.fill(value, start, end);

Example

const myArray = [1, 2, 3, 4, 5];
console.log(myArray);

myArray.fill(0, 1, 4);
console.log(myArray);

// Output:
// [1, 2, 3, 4, 5]
// [1, 0 0, 0, 5]

In this example, we first create an array myArray with five elements and log it to the console. Then we use the fill() method on myArray to change the values of all elements between the start index of 1 (inclusive) and the end index of 4 (exclusive) to the value of 0. Finally, we log the modified myArray to the console. The fill() method can also accept optional parameters for the start and end index. If both the start and end index are omitted, the entire Array will be filled with the specified value. If only the end index is omitted, the fill operation will be applied from the start index to the end of the Array.

7. from() Method

Creates a new array from an array-like or iterable object. The from() method is a built-in method that is used to create a new array from an array-like or iterable object. The array-like or iterable object can be any object with a length property or an object that implements an iterable protocol. This method returns a new array with elements copied from the original array-like or iterable object.

Syntax

Array.from(arrayLike, mapFn, thisArg);

Example

const myArrayLikeObject = {length: 3, 0: 'apple', 1: 'banana', 2: 'orange'};
const myArray = Array.from(myArrayLikeObject);
console.log(myArray);

// Output: ["apple", "banana", "orange"]

In this example, we create an array-like object myArrayLikeObject, with three elements and use the length property to specify the number of elements in the object. Then we use the Array.from() method to create a new array myArray from the myArrayLikeObject. The myArray contains the same elements as the myArrayLikeObject. The from() method can also accept an optional second argument, which is a map function used to transform the elements of the original array-like or iterable object before they are added to the new Array. This is useful when you need to modify the elements in the new Array, for example, by converting them to a different data type or changing their values.

8. join() Method

Joins all elements of an array into a string using a specified separator. The join() method is a built-in method that is used to join all elements of an array into a string using a specified separator. This method returns a new string that is created from concatenating all elements of the Array with the specified separator.

Syntax

arrayName.join(separator);

Example

const myArray = ['apple', 'banana', 'orange'];
const myString = myArray.join(', ');
console.log(myString);

// Output: "apple, banana, orange"

In this example, we create an array myArray with three elements and use the join() method to join all elements of the Array with the specified separator, The join() method returns a new string myString that contains the elements of the Array concatenated with the separator. Finally, we log the new string myString to the console. The join() method can also accept an optional separator parameter that determines the character or string used to separate the elements of the Array in the resulting string. If no separator is specified, a comma is used as the default separator.

9. toString() Method

Returns a string representing the specified Array and its elements. The toString() method is a built-in method that is used to return a string representing the specified Array and its elements. The method converts each element of the Array to a string and concatenates them together with commas in between. It returns a new string that represents the resulting string of all elements of the Array.

Syntax

arrayName.toString();

Example

const myArray = ['apple', 'banana', 'orange'];
const myString = myArray.toString();
console.log(myString);

// Output: "apple,banana,orange"

In this example, we create an array myArray with three elements and use the toString() method to convert the Array into a string. The toString() method returns a new string myString that contains all elements of the Array, separated by commas. Finally, we log the new string myString to the console. It's important to note that the toString() method differs from the join() method in that it does not allow the specification of a delimiter or separator. It always uses a comma as the separator between elements.

10. pop() Method

Removes the last element from an array and returns that element. The pop() method is a built-in method that is used to remove the last element from an array and return that element. This method modifies the original Array by removing the last element and returns the removed element.

Syntax

arrayName.pop();

Example

const myArray = ['apple', 'banana', 'orange'];
const lastElement = myArray.pop();
console.log(myArray);
console.log(lastElement);

// Output:
// ["apple", "banana"]
// "orange"

In this example, we create an array myArray with three elements and use the pop() method to remove the last element from the Array. The pop() method removes the element orange from the original array myArray and returns it as the last element. Finally, we log the modified myArray and the removed element last element to the console. The pop() method can be useful in situations where you need to remove the last element from an array, for example, when implementing a stack data structure or when you need to process elements of an array in reverse order.

11. forEach() Method

Executes a provided function once for each array element. The forEach() method is a built-in method that is execute a provided function once for each array element. The forEach() method is a higher-order function that accepts a callback function as its argument. The callback function is executed for each element of the Array, with the current element, the index of the element, and the entire Array passed as arguments.

Syntax

arrayName.forEach(callback(currentValue, index, array));

Example

const myArray = ['apple', 'banana', 'orange'];
myArray.forEach(function(element, index) {
   console.log(`${element} is at index ${index}`);
});

// Output:
// "apple is at index 0"
// "banana is at index 1"
// "orange is at index 2"

In this example, we create an array myArray with three elements and use the forEach() method to execute a callback function for each element of the Array. The callback function logs the element and its index to the console. The output shows that the callback function is executed for each element of the Array, with the element and its index passed as arguments. The forEach() method is commonly used when you need to iterate through all elements of an array and perform a specific action on each element. It's important to note that the forEach() method does not return a value, and it cannot be used to break out of a loop.

12. shift() Method

Removes the first element from an array and returns that element, shifting all subsequent elements to a lower index. The shift() method is a built-in method that is used to remove the first element from an array and return that element, shifting all subsequent elements to a lower index. This method modifies the original Array by removing the first element and returns the removed element.

Syntax

arrayName.shift();

Example

const myArray = ['apple', 'banana', 'orange'];
const firstElement = myArray.shift();
console.log(myArray);
console.log(firstElement);

// Output:
// ["banana", "orange"]
// "apple"

In this example, we create an array myArray with three elements and use the shift() method to remove the first element from the Array. The shift() method removes the element apple from the original array myArray and returns it as the first element. Finally, we log the modified myArray and the removed element first element to the console. The shift() method can be useful in situations where you need to remove the first element from an array, for example, when implementing a queue data structure. It's important to note, however, that the shift() method has a time complexity of O(n), where n is the number of elements in the Array because it needs to shift all subsequent elements to a lower index.

13. copywriting() Method

Copies a sequence of elements within the Array to another position in the same Array. The copyWithin() method is a built-in method that is used to copy a sequence of elements within the Array to another position in the same original Array by copying a portion of the Array to another location within the same Array. The copywithin(), the method accepts three arguments.

  • targetIndex: The index at which to start copying elements. This argument is required.
  • startIndex: The index from which to start copying elements. This argument is optional and defaults to 0 if not specified.
  • endIndex: The index at which to stop copying elements. This argument is optional and defaults to the length of the Array if not specified.

Syntax

arrayName.copyWithin(target, start, end);

Example

const myArray = ['apple', 'banana', 'orange', 'mango', 'watermelon'];
myArray.copyWithin(1, 3, 5);
console.log(myArray);

// Output:
// ["apple", "mango", "watermelon", "mango", "watermelon"]

In this example, we create an array myArray with five elements and use the copyWithin() method to copy a sequence of elements within the Array to another position in the same Array. We copy the elements starting from index 3 ('mango') and ending at index 5 ('watermelon') to index 1. The resulting Array has the sequence of copied elements at index 1 instead of their original position. The copyWithin() method can be useful when you need to manipulate an array in place, copying elements to another position to reorder the Array without creating a new array.

14. push() Method

Adds one or more elements to the end of an array and returns the new length of the Array. The push() method is a built-in method used to add one or more elements to the end of an array and returns the new length of the Array. This method modifies the original Array by adding the specified elements, and it returns the new length of the resulting Array.

Syntax

arrayName.push(element1, element2, ..., elementN);

Example

const myArray = ['apple', 'banana'];
const newLength = myArray.push('orange', 'mango');
console.log(myArray);
console.log(newLength);

// Output:
// ["apple", "banana", "orange", "mango"]
// 4

In this example, we create an array myArray with two elements and use the push() method to add two more elements to the end of the Array. The push() method adds the elements orange and mango to the original Array, and it returns the new length of the resulting Array as a new length. Finally, we log the modified myArray and the new length to the console. The push() method can be useful in situations where you need to add elements to the end of an array, expanding its size. It can also be used to combine multiple arrays by adding all elements from other arrays to the end of one Array.

15. unshift() Method

Adds one or more elements to the beginning of an array and returns the new length of the Array. the unshift() method is a built-in method that is used to add one or more elements to the beginning of an array and returns the new length of the Array. This method modifies the original Array by adding the specified elements at the beginning, and it returns the new length of the resulting Array.

Syntax

arrayName.unshift(element1, element2, ..., elementN);

Example

const myArray = ['apple', 'banana'];
const newLength = myArray.unshift('orange', 'mango');
console.log(myArray);
console.log(newLength);

// Output:
// ["orange", "mango", "apple", "banana"]
// 4

In this example, we create an array myArray with two elements and use the unshift() method to add two more elements to the beginning of the Array. The unshift() method adds the elements 'orange' and 'mango' at the beginning of the original Array, and it returns the new length of the resulting Array as a new length. Finally, we log the modified myArray and the new length to the console. The unshift() method can be useful in situations where you need to add elements to the beginning of an array, such as when implementing a queue data structure or when you need to modify indexes of existing elements in the Array.

16. concat() Method

 Returns a new array by merging two or more arrays. The concat() method is a built-in method that is used to merge two or more arrays into a new array. The concat() method creates a new array that includes all of the elements of the original arrays in the order in which they were specified.

Syntax

arrayName.concat(array1, array2, ..., arrayN);

Example

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [7, 8, 9];
const mergedArr = arr1.concat(arr2, arr3);
console.log(mergedArr);

// Output:
// [1, 2, 3, 4, 5, 6, 7, 8, 9]

In this example, we create three arrays, arr1, arr2, and arr3, and use the concat() method to merge them into a single array mergedArr. The concat() method concatenates the elements of all three arrays into a new array in the order in which they were specified. The concat() method does not modify the original arrays but instead returns a new array that contains the concatenated elements. It can also be used to concatenate arrays with other values, such as strings or numbers. The concat() method is commonly used when you need to merge two or more arrays into a single array or when you need to add new elements to an existing array without modifying the original Array.

17. some() Method

Checks if at least one element in the Array passes a provided condition (callback function). The some() method is a built-in method that is used to check if at least one element in the Array satisfies a provided condition (specified in a callback function). The some() method returns a boolean value (true or false) depending on whether any element in the Array meets the condition specified in the callback function.

Syntax

arrayName.some(callback(currentValue, index, array));

Example

const myArray = [1, 2, 3, 4, 5];
const hasEven = myArray.some(function(element) {
   return element % 2 === 0;
});
console.log(hasEven);

// Output:
// true

In this example, we create an array myArray with five elements and use the some() method to check if there is at least one even number in the Array. The callback function checks if each element in the Array is even, using the modulo operator (%) to check if the remainder is 0 when dividing by 2. The some() method returns true because the Array contains even numbers. The some() method stops iterating through the Array and returns true as soon as it finds the first element that satisfies the condition. If none of the elements satisfy the condition, it returns false. The some() method is commonly used to test if at least one element in the Array meets a specified condition, such as checking if the Array has any negative numbers, any numbers higher than a certain value, or any strings containing a particular character.

18. splice() Method

Changes the contents of an array by removing, replacing, or adding elements in place. The splice() method is a built-in method that is used to modify the contents of an array by removing, replacing, or adding elements in place. The splice() method can remove one or more elements from the Array, replace existing elements with new elements, or add new elements to the Array.

  • The splice(): method accepts three main arguments-
  • startIndex: The index at which to start changing the Array. This argument is required.
  • deleteCount: The number of elements to remove from the Array. If this argument is 0, no elements are removed. This argument is optional.

newElement1, newElement2, ...: The elements to add to the Array, starting at the startIndex. These arguments are optional.

Syntax

 arrayName.splice(start, deleteCount, item1, item2, ...);

Example

const myArray = ['apple', 'banana', 'orange'];
myArray.splice(1, 1, 'mango', 'pineapple');
console.log(myArray);

// Output:
// ["apple", "mango", "pineapple", "orange"]

In this example, we create an array myArray with three elements and use the splice() method to modify the contents of the Array. We start at index 1, remove 1 element ('banana'), and add two new elements ('mango' and 'pineapple') in their place. The resulting Array has four elements with modified contents. The splice() method can be very useful when you need to modify an array in place. It can also be used to extract a portion of an array into a new array by specifying the deleteCount argument and not specifying any new elements to add.

19. flat() Method

Creates a new array with all sub-array elements concatenated recursively up to the specified depth. The flat() method is a built-in method that is used to create a new array with all sub-array elements concatenated recursively up to the specified depth. The flat() method flattens a multidimensional array into a one-dimensional array by concatenating all sub-array elements. The flat() method can accept an optional argument depth that specifies the maximum depth of sub-arrays that should be flattened. If the depth argument is not specified, the flat() method flattens all levels of sub-arrays.

Syntax

arrayName.flat(depth);

Example

const nestedArray = [1, 2, [3, 4, [5, 6]]];
const flattenedArray = nestedArray.flat(2);
console.log(flattenedArray);

// Output:
// [1, 2, 3, 4, 5, 6]

In this example, we create a nested array with three levels of sub-arrays and use the flat() method to flatten all elements in the Array up to a maximum depth of 2. The result flattened Array has all sub-array elements concatenated recursively. The flat() method is commonly used to simplify complex arrays with nested sub-arrays by flattening them and making them easier to work with. It can also be used to filter out empty or non-existent values in an array by passing 0 as the depth argument.

20. lastIndexOf() Method

Returns the last index at which a specified element is found in an array. The lastIndexOf() method is a built-in method that is used to return the last index (position) at which a specified element is found in an array. The lastIndexOf() method searches the Array from right to left (from the end to the beginning) until it finds the specified element. The lastIndexOf() method can accept an optional argument fromIndex that specifies the position at which to start searching the Array from right to left. If the fromIndex argument is not specified, the lastIndexOf() method searches the entire Array.

Syntax

arrayName.lastIndexOf(searchElement, fromIndex);

Example

const myArray = ['apple', 'banana', 'orange', 'banana'];
const lastIndex = myArray.lastIndexOf('banana');
console.log(lastIndex);

// Output:
// 3

In this example, we create an array myArray with four elements and use the lastIndexOf() method to find the last index (position) of the string 'banana' in the Array. The lastIndexOf() method starts searching the Array from right to left and returns index 3, which is the index of the last occurrence, 'banana' in the Array. The lastIndexOf() method is commonly used to search an array for a specific element and return its last index (position) in the Array, particularly when working with arrays that may contain duplicate values.

21. of() Method

Creates a new array with the specified arguments as elements. The of() method is a built-in method that is used to create a new array with a variable number of elements. The of() method takes any number of arguments and returns a new array with the specified arguments as elements.

Syntax

 Array.of(element1, element2, ..., elementN);

Example

const myArray = Array.of(1, 'apple', true);
console.log(myArray);

// Output:
// [1, "apple", true]

In this example, we use the static Array method of() to create a new array myArray with three elements, an integer, a string, and a boolean value. The of every() method is useful when you need to create a new array with a variable number of elements, particularly when you do not know the values of the elements beforehand or when you need to pass a variable number of arguments to a function.

22. every() Method

Checks if all elements in the Array pass a provided condition (callback function). the every() method is a built-in method that is used to check if all elements in the Array pass a provided condition (specified in a callback function). The every() method returns a boolean value (true or false) depending on whether all elements in the Array meet the condition specified in the callback function.

Syntax

array.every(callback(currentValue, index, array);

Example

const myArray = [2, 4, 6, 8, 10];
const areEven = myArray.every(function(element) {
   return element % 2 === 0;
});
console.log(areEven);

// Output:
// true

In this example, we create an array myArray with five even numbers and use the every() method to check if all the elements in the Array are even. The callback function checks if each element in the Array is even, using the modulo operator (%) to check if the remainder is 0 when dividing by 2. Since all elements are even, the every() method returns true. The every() method stops iterating through the Array and returns false as soon as it finds the first element that does not satisfy the condition. If all of the elements satisfy the condition, it returns true. The every() method is commonly used to test if all elements in the Array meet a specified condition, such as checking if the Array has all positive integers, all numbers lower than a certain value, or all strings containing a particular character.

23. slice() Method

Returns a shallow copy of a portion of an array into a new array. slice() method is a built-in method that is used to return a shallow copy of a portion of an array into a new array. The slice() method creates a new array that includes the specified range of elements from the original Array without modifying the original Array.

The slice() the method accepts two main arguments:

  • startIndex: The index at which to begin slicing the Array. This argument is optional and defaults to 0.
  • endIndex: The index at which to end slicing the Array (the element at this index is not included in the sliced Array). This argument is optional and defaults to the end of the Array.

Syntax

array.slice(start, end);

Example

const myArray = ['apple', 'banana', 'orange', 'mango', 'pineapple'];
const slicedArray = myArray.slice(1, 4);
console.log(slicedArray);

// Output:
// ["banana", "orange", "mango"]

In this example, we create an array myArray with five elements and use the slice() method to create a new array slicedArray that includes elements from index 1 to index 3 (not including the element at index 4). The result slicedArray is a shallow copy of the portion of the original Array that was sliced. The slice() method is commonly used when you need to extract a portion of an existing array into a new array without modifying the original Array. It can also be used to create a copy of an array by calling slice() with no arguments.

24. flatMap() Method

Maps each element using a mapping function and flattens the result into a new array. The flatMap() method is a built-in method that is used to map each element in an array using a mapping function and then flattens the result into a new array. The flatMap() method is a combination of the map() and flat() methods, providing a more concise way to perform these operations together.

The flatMap() method accepts one main argument

  • mapping function:  A function that maps each element in the Array to a new value or Array.

Syntax

array.flatMap(callback(currentValue, index, array));

Example

const myArray = [1, 2, 3];
const mappedArray = myArray.flatMap(function(element) {
   return [element * 2, element * 3];
});
console.log(mappedArray);

// Output:
// [2, 3, 4, 6, 6, 9]

In this example, we create an array myArray with three elements and use the flatMap() method to map each element to a new array containing its doubled and tripled values. The result mappedArray is a flattened array of the mapped values. The flatMap() method is commonly used when you need to map each element in an array to multiple values, such as when working with arrays of objects or nested arrays. It provides a more concise way to perform these operations together than using map() and flat() separately. It's worth noting that the flatMap() method only flattens one level of nested arrays. If you need to flatten multiple levels of nested arrays, you can chain the flatMap() method with the flat() method as necessary.

25. findIndex() Method

Returns the index of the first element in the Array that satisfies the provided testing function. The findIndex() method is a built-in method that is used to return the index of the first element in an array that satisfies a provided testing function. The findIndex() method searches the Array from left to right until it finds an element that satisfies the testing function and returns the index of that element.

The findIndex() method accepts one main argument

testing function - A function that tests each element in the Array to see if it satisfies a certain condition. This function should return a boolean value (true or false).

Syntax

array.findIndex(callback(element, index, array))

Example

const myArray = ['apple', 'banana', 'orange', 'mango', 'pineapple'];
const index = myArray.findIndex(function(element) {
   return element === 'orange';
});
console.log(index);

// Output:
// 2

In this example, we create an array myArray with five elements and use the findIndex() method to search for the index of the string 'orange' in the Array. The callback function tests each element in the Array to see if it equals 'orange', and returns true when it finds the matching element. The findIndex() method then returns index 2, which is the index of the first occurrence of 'orange' in the Array. The findIndex() method is commonly used to search an array for a specific element that meets a certain condition and returns its index in the Array. If no element is found, the findIndex() method returns -1.

26. find() Method

Returns the value of the first element in the Array that satisfies the provided testing function. The find() method is a built-in method that is used to return the value of the first element in an array that satisfies a provided testing function. The find() method searches the Array from left to right until it finds an element that satisfies the testing function and returns the value of that element.

The find() method accepts one main argument

  • testing function:  A function that tests each element in the Array to see if it satisfies a certain condition. This function should return a boolean value (true or false).

Syntax

array.find(callback(element, index, array));

Example

const myArray = [2, 4, 6, 8, 10];
const foundElement = myArray.find(function(element) {
   return element > 5;
});
console.log(foundElement);

// Output:
// 6

In this example, we create an array myArray with five even numbers and use the find() method to search for the first element in the Array that is greater than 5. The callback function tests each element in the Array to see if it is greater than 5 and returns true when it finds the matching element. The find() method then returns the value, which is the first element in the Array that satisfies the condition. The find() method is commonly used to search an array for a specific element that meets a certain condition and returns its value. If no element is found, the find() method returns undefined.

27. includes() Method

Determines whether an array includes a certain element, returning true or false. The includes() method is a built-in method that is used to determine whether an array includes a certain element, returning a boolean value (true or false) depending on whether the element is found in the Array.

The includes() the method accepts two arguments

  • search element: The element to search for in the Array.
  • startIndex: The index at which to begin searching the Array (optional).

Syntax

array.includes(searchElement, fromIndex);

Example

const myArray = ['apple', 'banana', 'orange', 'mango', 'pineapple'];
const hasPineapple = myArray.includes('pineapple');
console.log(hasPineapple);

// Output:
// true

In this example, we create an array myArray with five elements and use the includes() method to search for the string 'pineapple' in the Array. The includes() method returns true since 'pineapple' is in the. The includes() method is commonly used to check if an array contains a specific element, such as when verifying user input or filtering data based on certain criteria. If the startIndex argument is specified, the includes() method will start searching the Array from that index instead of the beginning of the Array.

28. entries() Method

Returns a new Array Iterator object that contains the key/value pairs for each index in the Array. The entries() method is a built-in method that is used to return a new Array Iterator object that contains the key/value pairs for each index in the Array. The entries() method creates an iterator object that can be used to loop through the Array and iterate over its elements.

Syntax

array.entries();

Example

const myArray = ['apple', 'banana', 'orange'];
const entries = myArray.entries();
console.log(entries.next().value);
console.log(entries.next().value);
console.log(entries.next().value);

// Output:
// [0, "apple"]
// [1, "banana"]
// [2, "orange"]

In this example, we create an array myArray with three elements and use the entries() method to create an iterator object entries. We then use the next() method to iterate over the elements in the iterator object and print out the key/value pairs for each index in the Array. The entries() method is commonly used when you need to iterate over the elements in an array along with their index values, such as when working with associative arrays or when constructing new objects or maps. It's worth noting that the entries() method is only available in ECMAScript 6 (ES6) or higher versions of JavaScript. If you need to create an iterator object in earlier versions of JavaScript, you can use the forEach() method or implement your custom iterator.

29. reduceRight() Method

Applies a function against an accumulator and each element in the Array (from right to left) to reduce it to a single value. The reduceRight() method is a built-in method that is used to apply a function against an accumulator and each element in the Array, from right to left, to reduce it to a single value. The reduceRight() method is similar to the reduce() method, but it iterates over the elements in the Array in reverse order.

The reduceRight() method accepts two main arguments

  • reducer function: The function to apply against the accumulator and each element in the Array. This function should take two arguments: the accumulator and the current element of the Array.
  • initialValue: The initial value of the accumulator (optional). If this argument is not provided, the method will start with the last element of the Array as the initial value.

Syntax

array.reduceRight(callback(accumulator, currentValue, index, array), initialValue);

Example

const myArray = [1, 2, 3, 4, 5];
const sum = myArray.reduceRight(function(accumulator, currentValue) {
  return accumulator + currentValue;
});
console.log(sum);

// Output:
// 15

In this example, we create an array myArray with five numbers and use the reduceRight() method to apply a function that adds each element in the Array to the accumulator, from right to left. The resulting sum is the total sum of all the elements in the Array, which is 15. The reduceRight() method is commonly used when you need to operate on an array from right to left, such as when working with strings or calculating totals that are dependent on earlier values in the Array. It's worth noting that the reduceRight() method is not supported in older versions of Internet Explorer and some other browsers, so you may need to use a polyfill or implement your custom solution if you are targeting those environments.

30. reduce() Method

Applies a function against an accumulator and each element in the Array (from left to right) to reduce it to a single value. The reduce() method is a built-in method that is used to apply a function against an accumulator and each element in the Array, from left to right, to reduce it to a single value. The reduce() method can be used to sum the values in an array, concatenate strings, or perform any other aggregation or calculation on an array.

The reduce() method accepts two main arguments,

  • reducer function: The function to apply against the accumulator and each element in the Array. This function should take two arguments: the accumulator and the current element of the Array.
  • initialValue: The initial value of the accumulator (optional). If this argument is not provided, the method will start with the first element of the Array as a value.

Syntax

array.reduce(callback(accumulator, currentValue, index, array), initialValue);

Example

const myArray = [1, 2, 3, 4, 5];
const sum = myArray.reduce(function(accumulator, currentValue) {
  return accumulator + currentValue;
});
console.log(sum);

// Output:
// 15

In this example, we create an array myArray with five numbers and use the reduce() method to apply a function that adds each element in the Array to the accumulator, from left to right. The resulting sum is the total sum of all the elements in the Array, which is 15. The reduce() method is commonly used when you need to operate on an array, such as calculating totals, aggregating data, or transforming array values. It's worth noting that the reduce() method is not supported in older versions of Internet Explorer and some other browsers, so you may need to use a polyfill or implement your custom solution if you are targeting those environments.

31. isArray() Method

Determines whether the passed value is an array. The isArray() method is a built-in method that is used to determine whether a passed value is an array. The isArray() method returns a boolean value (true or false) depending on whether the value is an array or not.

The isArray() method only has one argument,

  • value: The value to be tested.

Syntax

Array.isArray(value);

Example

const myArray = [1, 2, 3, 4, 5];
const isAnArray = Array.isArray(myArray);
console.log(isAnArray);

// Output:
// true

In this example, we create an array myArray with five numbers and use the isArray() method to determine whether myArray is an array. The isArray() method returns true since myArray is indeed an array. The isArray() method is commonly used when you need to check if a value is an array or not, especially when working with data from dynamic sources like user input or external APIs. This method helps you ensure that you are working with the correct data type and avoid errors and bugs in your code. It's worth noting that the isArray() method is only available in ECMAScript 5 (ES5) or higher versions of JavaScript. If you need to test if a value is an array in earlier versions of JavaScript, you can use the type of operator or the instance of the operator to check the object's prototype.

32. filter() Method

Creates a new array with all elements that pass the provided condition (callback function). The filter() method is a built-in array method that creates a new array with all elements that pass the provided condition (callback function). The filter() method iterates through an array and returns a new array containing only the elements that satisfy the condition specified in the callback function.

The filter() method accepts one main argument,

  • callback function:  A function that tests each element in the Array for a specified condition. If the element meets the condition, it is included in the new Array. This function should return a boolean value (true or false).

Syntax

array.filter(callback(element, index, array));

Example

const myArray = [1, 2, 3, 4, 5];
const result = myArray.filter(function(element) {
  return element % 2 === 0;
});
console.log(result);

// Output:
// [2, 4]

In this example, we create an array myArray with five numbers and use the filter() method to create a new array result that contains only the even numbers from the original Array. The callback function tests each element in the Array to see if it is divisible by 2 (i.e., even) and returns true if it is. The resulting result array contains only the even numbers [2, 4]. The filter() method is commonly used when you need to extract a subset of elements from an array that meets certain criteria, such as positive numbers, strings that contain a certain substring, or objects with specific properties. It's worth noting that the filter() method does not modify the original Array; it creates a new array with the filtered elements, leaving the original Array unchanged.

33. keys() Method

Returns a new Array Iterator object that contains the keys for each index in the Array. the keys() method is a built-in method that returns a new Array Iterator object that contains the keys for each index in the Array. The keys() method creates an iterator object that can be used to loop through the Array and iterate over the keys for each index.

Syntax

array.keys();

Example

const myArray = ['dog', 'cat', 'rabbit'];
const iterator = myArray.keys();
for (const key of iterator) {
  console.log(key);
}

// Output:
// 0
// 1
// 2

In this example, we create an array myArray with three elements and use the keys() method to create an iterator object iterator. We then use a for..of the loop to iterate over the keys for each index in the Array, printing out the key for each index. The keys() method is commonly used when you need to access the keys for each index in an array, such as when iterating over the Array and performing operations on each element. It's worth noting that the keys() method is only available in ECMAScript 6 (ES6) or higher versions of JavaScript. If you need to access the keys for each index in an array in earlier versions of JavaScript, you can use a traditional for loop to iterate over the Array and access each index directly.

34. map() Method

Description: Creates a new array with the results of calling a provided function on every element in the Array. The map() method is a built-in method that is used to create a new array with the results of calling a provided function on every element in the Array. The map() method applies the provided function to each element in the Array and returns a new array with the resulting values.

The map() method accepts one main argument,

  • callback function: The function to call on each element in the Array. This function should return the modified value for each element.

Syntax

array.map(callback(element, index, array));

Example

const myArray = [1, 2, 3];
const result = myArray.map(function(element) {
  return element + 1;
});
console.log(result);

// Output:
// [2, 3, 4]

In this example, we create an array myArray with three numbers and use the map() method to create a new array result that contains each number incremented by 1. The callback function applies the +1 operation to each element in the Array, and the resulting result array contains [2, 3, 4]. The map() method is commonly used when you need to transform each element in an array and create a new array with the transformed values, such as when converting units of measurement, formatting data, or performing other operations on array elements. It's worth noting that the map() method does not modify the original Array; it creates a new array with the transformed values, leaving the original Array unchanged.

Conclusion

In conclusion, JavaScript provides a variety of powerful array methods that allow developers to manipulate and work with arrays effectively. These methods, such as value(), length(), reverse(), sort(), and others, enable tasks like accessing array elements, modifying arrays, iterating over elements, and more. Understanding and utilizing these methods can greatly enhance JavaScript programming capabilities. JavaScript offers a rich selection of array methods that empower developers to effectively work with arrays. These methods enable tasks such as adding or removing elements, modifying array content, searching for specific values, and more. With methods, elements can be appended to an array, while map() allows for the transformation of each element based on a provided function. Filtering an array based on specific criteria can be achieved using filter(), and reducing an array to a single value is made possible with reduce(). These array methods, along with others, provide powerful tools to manipulate, iterate, and extract information from arrays in JavaScript.

FAQ's

Q1. What is the difference between map() and forEach() array methods in JavaScript?

Ans. The map() method creates a new array by applying a provided function to each element, while the forEach() method executes a provided function for each element without creating a new array.

Q2. How can I remove a specific element from an array using JavaScript?

Ans. To remove a specific element from an array, you can use methods like filter() or splice() based on the condition or index of the element you want to remove.

Q3 - Can I use multiple array methods together in JavaScript?

Ans. Yes, you can chain multiple array methods together to perform complex operations on arrays. For example, you can use map().filter().reduce() to transform, filter, and reduce an array in a single statement.

Q4 - What is the purpose of the sort() method in JavaScript?

Ans. The sort() method allows you to sort the elements of an array in place, either alphabetically or based on a custom sorting function.

Q5 - How can I check if an array is empty using JavaScript?

Ans. You can use the length property of an array to check if it is empty. If the length is 0, the Array is considered empty.

Q6 - Can I reverse the order of elements in an array using JavaScript?

Ans. Yes, the reverse() method can be used to reverse the order of elements in an array in place.

Q7 - How can I join the elements of an array into a single string in JavaScript?

Ans. The join() method allows you to concatenate the elements of an array into a string using a specified separator.

Q8 - How can I copy the elements of one Array to another in JavaScript?

Ans. You can use methods like slice() spread syntax ([... Array]) to create a shallow copy of an array.

Q9 - How can I check if a value exists in an array using JavaScript?

Ans. The includes() method can be used to check if an array contains a specific value, returning true or false.

Q10 - How can I iterate over the key-value pairs of an array in JavaScript?

Ans. You can use the entries() method to get an iterator of key-value pairs for each index in the Array, which can be iterated using a loop or a for...of statement.