DEV Community

Cover image for Mastering JavaScript Array Methods: Your Ultimate Guide
Jaimal Dullat
Jaimal Dullat

Posted on • Originally published at Medium

Mastering JavaScript Array Methods: Your Ultimate Guide

Table of Contents

  1. Creating New Array

  2. Adding Elements to Array

  3. Removing Elements from Array

  4. Search for Specific Elements

  5. Iterating Over Array

  6. Copying an Array

  7. Sorting and Reversing an Array

  8. Accessing Array Element

  9. Transforming Arrays

  10. Miscellaneous Methods

  11. Conclusion


Creating New Array

array literal syntax

  • You can create an array using square brackets and specifying its elements within the brackets.
let fruits = ["apple", "banana", "orange"];
Enter fullscreen mode Exit fullscreen mode

array constructor

  • You can also create an array using the Array constructor.
let fruits = new Array("apple", "banana", "orange");
Enter fullscreen mode Exit fullscreen mode

Be cautious when using the Array constructor with a single numeric argument, as it specifies the length of the array rather than the elements.

let emptyArray = new Array(5); 
// Creates an array with 5 undefined elements
Enter fullscreen mode Exit fullscreen mode

of() method

  • The of() method in JavaScript is used to create a new array instance with a set of provided values.

  • It is a static method, meaning it is called on the array constructor itself, and it returns a new array containing the provided values.

const myArray = Array.of("apple", "banana", "orange");
console.log(myArray); // Output: ["apple", "banana", "orange"]
Enter fullscreen mode Exit fullscreen mode

Adding Elements to Array

push() method

  • The push() method adds one or more elements to the end of an array.
// adding 1 element
let fruits = ["apple", "banana", "cherry"];
fruits.push("orange");

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


// adding multiple elements
let fruits = ["apple", "banana", "cherry"];
fruits.push("orange", "date");

console.log(fruits); // Output: ["apple", "banana", "cherry", "orange", "date"]
Enter fullscreen mode Exit fullscreen mode

unshift() method

  • The unshift() method adds one or more elements to the beginning of an array.
// adding 1 element
let fruits = ["banana", "cherry"];
fruits.unshift("apple");

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

// adding multiple elements
let fruits = ["banana", "cherry"];
fruits.unshift("apple", "orange");

console.log(fruits); // Output: ["apple", "orange", "banana", "cherry"]
Enter fullscreen mode Exit fullscreen mode

array indexing

  • You can also add an item to a specific index by directly assigning a value to that index.
let fruits = ["apple", "banana", "cherry"];
fruits[2] = "orange";

console.log(fruits); // Output: ["apple", "banana", "orange"]
Enter fullscreen mode Exit fullscreen mode

splice() method

  • The splice() method to add elements to an array at a specified position.

  • The splice() method can also be used to remove elements from an array

Syntax:

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

  • start: The index at which to start changing the array. If negative, it will count from the end of the array.

  • deleteCount: An integer indicating the number of old elements to remove. If set to 0, no elements will be removed. If omitted or undefined, all elements from start to the end of the array will be removed.

  • item1, item2, ...: The elements to add to the array at the specified start position.

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

// Insert 'orange' at index 1, replacing 0 elements
fruits.splice(1, 0, "orange"); // Output: ["apple", "orange", "banana", "cherry"]

// Insert 'grape' at index 2, replacing 1 element
fruits.splice(2, 1, "grape"); // Output: ["apple", "banana", "grape", "cherry"]

// Insert 'kiwi' at the end of the array
fruits.splice(fruits.length, 0, "kiwi"); // Output: ["apple", "orange", "grape", "cherry", "kiwi"]
Enter fullscreen mode Exit fullscreen mode

Removing Elements from Array

pop() method

  • The pop() method removes the last element from an array.

  • It modifies the original array.

  • It returns the removed element.

let fruits = ["apple", "banana", "cherry"];
let removedElement = fruits.pop(); // Removes "cherry"

console.log(removedElement); // Output: "cherry"
console.log(fruits); // Output: ["apple", "banana"]
Enter fullscreen mode Exit fullscreen mode

shift() method

  • The shift() method removes the first element from an array.

  • It modifies the original array.

  • It returns the removed element.

let fruits = ["apple", "banana", "cherry"];
let removedElement = fruits.shift(); // Removes "apple"

console.log(removedElement); // Output: "apple"
console.log(fruits); // Output: ["banana", "cherry"]
Enter fullscreen mode Exit fullscreen mode

splice() method

  • The splice() method can be used to delete or add elements from an array by specifying the index and the number of elements to be removed.

  • It modifies the original array.

  • It returns the removed element.

Syntax:

array.splice(startIndex, deleteCount);

  • array: The array you want to modify.

  • startIndex: The index at which the modification should begin. If negative, it counts from the end of the array

  • deleteCount: The number of elements to remove from the array starting at the start index. If set to 0, no elements will be removed.

let fruits = ["apple", "banana", "orange", "grape"];
let removedElements = fruits.splice(1, 2); // Removes "banana" and "orange"

console.log(removedElements) // Output: ["banana", "orange"]
console.log(fruits); // Output: ['apple', 'grape']
Enter fullscreen mode Exit fullscreen mode

delete operator

  • The delete operator can be used to delete an element from an array, but it doesn't actually remove the element; it replaces it with undefined.
let fruits = ["apple", "banana", "cherry"];
delete fruits[1]; // Sets index 1 to undefined

console.log(fruits); // Output: ["apple", undefined, "cherry"]
Enter fullscreen mode Exit fullscreen mode

Search for Specific Elements

includes() method

  • The includes() method checks if an array includes a specific item

  • It returns a boolean value (true if found, false otherwise).

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

console.log(fruits.includes("apple"));  // Output: true
console.log(fruits.includes("grape"));  // Output: false
Enter fullscreen mode Exit fullscreen mode

indexOf() method

  • The indexOf() method returns the index of the first occurrence of a specified item in an array.

  • It returns the index of the element if the item is found, otherwise, it returns -1.

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

const firstIndexOfApple= fruits.indexOf('apple');
console.log('First index of apple:', firstIndexOfApple); // Output: 0

const firstIndexOfGrape= fruits.indexOf('grape');
console.log('First index of grape:', fruits.indexOf('grape')); // Output: -1
Enter fullscreen mode Exit fullscreen mode

lastIndexOf() method

  • The lastIndexOf() method is another array method that is similar to indexOf().

  • It searches for the last occurrence of a specified element within the array.

const fruits = ['apple', 'banana', 'orange', 'apple'];
const lastIndex = fruits.lastIndexOf('apple');

console.log('Last index of apple:', lastIndex);  // Output: 3
Enter fullscreen mode Exit fullscreen mode

find() method

  • The find() method returns the first element in an array that satisfies a provided testing function.
const fruits = ["apple", "banana", "cherry"];
const itemToFind = "banana";

const foundItem = fruits.find(fruit => fruit === itemToFind);

if (foundItem) {
    console.log(`${itemToFind} is in the array.`);
} else {
    console.log(`${itemToFind} is not in the array.`);
}
Enter fullscreen mode Exit fullscreen mode

findLast() method

  • The findLast() method is another array method that is similar to find().

  • It searches for the last occurrence of a specified element within the array.

const array1 = [5, 12, 50, 130, 44];
const found = array1.findLast((element) => element > 45);

console.log(found); // Output: 130

Enter fullscreen mode Exit fullscreen mode

findIndex() method

  • The findIndex() method in JavaScript is used to find the index of the first element in an array that satisfies a provided testing function.

  • It returns the index of the first element that meets the condition, or -1 if no such element is found.

const numbers = [10, 20, 30, 40, 50];

// Find the index of the first element greater than 25
const index = numbers.findIndex((element) => element > 25);

console.log(index); // Output: 2 (index of the element 30)
Enter fullscreen mode Exit fullscreen mode

findLastIndex() method

  • The findIndex() method in JavaScript is used to find the index of the last element in an array that satisfies a provided testing function.

  • It searches for the last occurrence of a specified element within the array.

const numbers = [10, 20, 30, 40, 50];

// Find the index of the last element greater than 25
const index = numbers.findLastIndex((element) => element > 25);
console.log(index); // Output: 4(index of the element 50)
Enter fullscreen mode Exit fullscreen mode

Iterating Over Array

for loop

  • The traditional for loop can be used to iterate over an array by incrementing an index variable.
const array = [1, 2, 3, 4, 5];
for (let i = 0; i < array.length; i++) {
   console.log(array[i]);
}
Enter fullscreen mode Exit fullscreen mode

for…of loop

  • The for...of loop is a simpler way to iterate over arrays.
const array = [1, 2, 3, 4, 5];
for (const element of array) {
   console.log(element);
}
Enter fullscreen mode Exit fullscreen mode

forEach method

  • The forEach() method is a built-in method for arrays that allows you to execute a function for each element in the array.
const array = [1, 2, 3, 4, 5];
array.forEach(function (element) {
  console.log(element);
});
Enter fullscreen mode Exit fullscreen mode

while loop

  • You can also use a while loop to iterate over an array.
 const array = [1, 2, 3, 4, 5];
let i = 0;
while (i < array.length) {
  console.log(array[i]);
  i++;
}
Enter fullscreen mode Exit fullscreen mode

Copying an Array

spread operator (…)

  • The spread operator (...) can be used to create a shallow copy of an array.
const originalArray = [1, 2, 3];
const copiedArray = [...originalArray];

console.log(copiedArray); // [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

slice() method

  • The slice() method can be used to copy a portion of an array, or the entire array if no arguments are provided.

  • It does not modify the original array.

  • You can use negative indices.

Example 1: Copying the entire array

 const fruits = ['apple', 'banana', 'orange', 'grape', 'cherry'];
const slicedFruits = fruits.slice();

console.log(slicedFruits); // ['apple', 'banana', 'orange', 'grape', 'cherry']
Enter fullscreen mode Exit fullscreen mode

In this example, slice() without arguments creates a shallow copy of the fruits array.

Example 2: Slicing with start and end indices

const fruits = ['apple', 'banana', 'orange', 'grape', 'cherry'];
const slicedFruits = fruits.slice(1, 4);

console.log(slicedFruits); // ["banana", "orange", "grape"]
Enter fullscreen mode Exit fullscreen mode

Here, slice(1, 4) extracts elements from index 1 (inclusive) to index 4 (exclusive).

Example 3: Negative indices and omitting the end index:

const fruits = ['apple', 'banana', 'orange', 'grape', 'cherry'];
const slicedFruits = fruits.slice(-3);

console.log(slicedFruits); // ["orange", "grape", "cherry"]
Enter fullscreen mode Exit fullscreen mode

In this case, we only specify the start index, so it slices from the specified index to the end of the array.

concat() method

  • The concat() method can be used to merge two or more arrays, creating a new array as a copy.

  • It doesn’t modify the original array.

// example 1
const originalArray = [1, 2, 3];
const copiedArray = [].concat(originalArray);

console.log(copiedArray); // [1, 2, 3]

// example 2
const firstArray = [1, 2, 3];
const secondArray = [5, 6, 8];
const mergedArray= firstArray.concat(secondArray);

console.log(mergedArray); // [1, 2, 3, 5, 6, 8]
Enter fullscreen mode Exit fullscreen mode

from() method

  • The Array.from() method can be used to create a shallow copy of an array-like object or iterable.
const originalArray = [1, 2, 3];
const copiedArray = Array.from(originalArray);

console.log(copiedArray); // [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

map() method

  • You can use the map() method to create a new array with the same values.
const originalArray = [1, 2, 3];
const copiedArray = originalArray.map(item => item);

console.log(copiedArray); // Output:  [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

for loop

  • You can manually copy the elements of the array using a for loop.
const originalArray = [1, 2, 3];
const copiedArray = [];

for (let i = 0; i < originalArray.length; i++) {
  copiedArray.push(originalArray[i]);
}

console.log(copiedArray); // Output: [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

copyWithin() method

  • The copyWithin() method is used to copy a portion of an array to another location within the same array, overwriting existing elements if needed.

  • It operates on the array in place, without changing its length.

Syntax:
array.copyWithin(target, start, end)

  • target (required): The index at which to start copying elements to.

  • start (optional): The index at which to start copying elements from (default is 0).

  • end (optional): The index at which to stop copying elements from (default is the end of the array).

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

// Copy elements starting from index 2 to index 0
array.copyWithin(0, 2);

console.log(array); // Output: [3, 4, 5, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Note that these methods create shallow copies, meaning that if the original array contains objects or other arrays, the copied array will still reference the same objects. If you need a deep copy (a copy where nested objects and arrays are also cloned), you’ll need to implement a custom deep copy function or use a library like Lodash’s _.cloneDeep().


Sorting and Reversing an Array

In JavaScript, you can sort an array using various methods. The primary method is the sort() method provided by the Array object, which sorts elements in place and converts elements to strings for comparison by default. However, you can also provide a custom comparison function to control the sorting order. Here are some examples of sorting an array in JavaScript:

sort() method: default comparison

  • without a custom comparison function
const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
fruits.sort();

console.log(fruits); // Outputs: ['apple', 'banana', 'cherry', 'date', 'elderberry']
Enter fullscreen mode Exit fullscreen mode

sort() method: custom comparison function

  • numeric sorting in ascending order
const numbers = [10, 5, 8, 1, 7];
numbers.sort((a, b) => a - b);

console.log(numbers); // Outputs: [1, 5, 7, 8, 10]
Enter fullscreen mode Exit fullscreen mode

In this case, the function subtracts b from a, and if the result is negative, it means ashould be placed before b.

sort() method: custom comparison function

  • reverse alphabetical sorting
const words = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
words.sort((a, b) => b.localeCompare(a));

console.log(words); // Outputs: ['elderberry', 'date', 'cherry', 'banana', 'apple']
Enter fullscreen mode Exit fullscreen mode
  • The localeCompare() method compares two strings in the current locale.

  • The localeCompare() method returns sort order -1, 1, or 0 (for before, after, or equal).

reverse() method

  • You can reverse an array in JavaScript using the reverse() method.

  • This method reverses the order of the elements in the array in place, without creating a new array.

let numbers = [1, 2, 3, 4, 5];
console.log("Original array:", numbers); // Original array: [1, 2, 3, 4, 5]

numbers.reverse();

console.log("Reversed array:", numbers); // Reversed array: [5, 4, 3, 2, 1]
Enter fullscreen mode Exit fullscreen mode

If you want to reverse an array without modifying the original array, you can create a copy of the array and then reverse the copy:

let numbers = [1, 2, 3, 4, 5];
let reversedNumbers = [...numbers].reverse();

console.log("Original array:", numbers);
console.log("Reversed array:", reversedNumbers);
Enter fullscreen mode Exit fullscreen mode

In this case, reversedNumbers contains the reversed elements, and the original numbers array remains unchanged.


Accessing Array Element

bracket notation

  • You can use square brackets [] with the index to access an element from an array.
const fruits = ["apple", "banana", "cherry"];
const firstFruit = fruits[0]; // Access the first element (index 0)

console.log(firstFruit); // Output: "apple"
Enter fullscreen mode Exit fullscreen mode

at() method:

  • The at() method in JavaScript is used to access the element at a specific index in an array.

  • It is a convenient way to retrieve a particular element without the need for iteration or looping.

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

console.log(fruits.at(2)); // Output: 'orange'
Enter fullscreen mode Exit fullscreen mode

array destructuring

  • You can use array destructuring to assign array elements to individual variables.
const fruits = ["apple", "banana", "cherry"];
const [firstFruit, secondFruit] = fruits;

console.log(firstFruit); // Output: "apple"
console.log(secondFruit); // Output: "banana"
Enter fullscreen mode Exit fullscreen mode

Array.prototype Methods

  • JavaScript provides several array methods to access elements by index, such as array.slice(), array.splice(), and array.concat().
const fruits = ["apple", "banana", "cherry"];
const secondFruit = fruits.slice(1, 2); // Access the second element using slice
console.log(secondFruit); // Output: ["banana"]
Enter fullscreen mode Exit fullscreen mode

for loop

  • You can use a for loop to iterate through the array and access elements by their indices.
const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]); // Output: "apple", "banana", "cherry"
}
Enter fullscreen mode Exit fullscreen mode

Transforming Arrays

reduce() method

  • Applies a function against an accumulator and each element in the array to reduce it to a single value.
const arr = [1, 2, 3, 4];
const sum = arr.reduce((acc, curr) => acc + curr, 0);

console.log(sum); // Output: 10
Enter fullscreen mode Exit fullscreen mode

reduceRight() method

  • The reduceRight() method in JavaScript is used to reduce the elements of an array from right to left, applying a given function to accumulate a single result.

  • It is similar to the reduce method, but processes the array in reverse order.

const fruitName = ['e', 'l', 'p', 'p', 'a'];

const fruit = fruitName.reduceRight((accumulator, currentValue) => accumulator + currentValue);

console.log(fruit); // Output: apple (a + p + p + l + e)
Enter fullscreen mode Exit fullscreen mode

concat()

  • Used to merge two or more arrays.
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const merged = arr1.concat(arr2);

console.log(merged); // Output: [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

fill() method

  • The fill() method in JavaScript is used to change all elements in an array to a specified value.

  • It modifies the original array in place and returns the modified array.

Syntax:

array.fill(value, start, end)

  • value: The value to fill the array with.

  • start (optional): The index at which to start filling (default is 0).

  • end (optional): The index at which to stop filling (default is the length of the array).

const numbers = [1, 2, 3, 4, 5];
numbers.fill(0, 2, 4);

console.log(numbers); // Output: [1, 2, 0, 0, 5]
Enter fullscreen mode Exit fullscreen mode

filter() method

  • The filter() method in JavaScript is used to create a new array by filtering out elements from an existing array based on a specified condition.

  • It does not modify the original array but returns a new array containing only the elements that meet the specified criteria.

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

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

console.log(evenNumbers); // Output: [2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

join() method

  • The join() method in JavaScript is used to create a new string by joining all the elements of an array together into a single string, with an optional delimiter between each element.
const fruits = ['apple', 'banana', 'cherry'];
const joinedString = fruits.join(', ');

console.log(joinedString); // Output: "apple, banana, cherry"
Enter fullscreen mode Exit fullscreen mode

toString() method

  • The JavaScript toString() method is used to convert an array into a string representation.

  • It returns a comma-separated string containing the elements of the array.

const fruits = ["apple", "banana", "cherry"];
const fruitString = fruits.toString();

console.log(fruitString); // Output: "apple,banana,cherry"
Enter fullscreen mode Exit fullscreen mode

Miscellaneous Methods

length property

  • Returns the number of elements in an array.
const arr = [1, 2, 3];
console.log(arr.length); // Output: 3
Enter fullscreen mode Exit fullscreen mode

isArray() method

  • Determines whether the passed value is an array.
const arr = [1, 2, 3];
const notArr = "Hello, world!";

console.log(Array.isArray(arr));    // true
console.log(Array.isArray(notArr)); // false
Enter fullscreen mode Exit fullscreen mode

every() method

  • The every() method in JavaScript is used to check if all elements in an array satisfy a specified condition.

  • It returns a boolean value indicating whether all elements meet the condition.

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

// Check if all elements are greater than 0
const allGreaterThanZero = numbers.every((element) => {
  return element > 0;
});

console.log(allGreaterThanZero); // Output: true
Enter fullscreen mode Exit fullscreen mode

flat() method

  • The flat() method is used to flatten a nested array by removing one level of nesting.

  • It returns a new array with all the elements from the nested arrays concatenated into a single array.

Syntax:

let newArray = arr.flat([depth]);

  • arr: The original array that you want to flatten.

  • depth (optional): Specifies how deep to flatten the array. By default, it flattens one level, but you can provide a number to indicate the depth to which the array should be flattened.

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

console.log(flatArray);
// Output: [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

faltMap() method

  • The flatMap() method is used to both map and flatten an array by applying a specified function to each element and then flattening the result into a new array.

  • It is often used when you have an array of arrays and want to transform and combine them into a single array.

Syntax:

array.flatMap(callback(currentValue[, index[, array]])[, thisArg])

  • callback: A function to execute on each element of the array.

  • currentValue: The current element being processed in the array.

  • index (optional): The index of the current element.

  • array (optional): The array flatMap was called upon.

  • thisArg (optional): Value to use as this when executing the callback.

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

const result = arr.flatMap(x => [x, x * 2]);

console.log(result); // Output: [1, 2, 2, 4, 3, 6, 4, 8, 5, 10]
Enter fullscreen mode Exit fullscreen mode

Conclusion

In conclusion, JavaScript provides a rich set of array methods that cater to different needs and use cases. By categorizing these methods based on their functionality, developers can easily identify and choose the appropriate method for their specific requirements.

Whether you need to modify arrays, access their values without altering them, iterate over their elements, search for specific items, transform their structure, sort their elements, or perform other utility operations, JavaScript has got you covered with its comprehensive array methods.

🔗 Connect with me on:

A Big Thank You! 🌟

  • Readers: Grateful for every click and read.
  • Engagers: Claps, comments, shares — you’re the best!
  • Followers: Honored by your continuous support.
  • Silent Admirers: Your presence doesn’t go unnoticed.
  • Constructive Critics: Your insights help us improve.

💌 Stay connected and thanks for being part of our journey.

Top comments (0)