Mastering Array Methods in JavaScript: Your Guide to Becoming a JavaScript Ninja

Ashwini Paraye
20 min readApr 29, 2023

--

array methods

Are you tired of manually sorting, filtering, or manipulating arrays in JavaScript? Fear not, because JavaScript comes with an array of powerful built-in methods to make your life easier. In this article, we will explore array methods with plenty of examples. Are you ready to dive into the wonderful world of arrays in JavaScript? Well, grab a cup of coffee and let’s get started!

First things first, what is an array? Simply put, an array is a collection of values. These values can be of any type, including numbers, strings, objects, or even other arrays. Arrays are incredibly useful for storing and organizing data, making them a fundamental part of any programming language, including JavaScript.

Array

Let’s take a look at an example to see how arrays work. Imagine you’re planning a road trip and you want to create a list of all the places you want to visit. You could create an array like this :

let roadTrip = ["Darjeeling", "Mysore", "Varanasi", "Agra"];

In this example, we’ve created an array called roadTrip that contains the names of four different cities we want to visit. Notice that each value is enclosed in quotes and separated by a comma.

Now that we have our array, we can access its values using their index. In JavaScript, arrays are zero-indexed, meaning the first value has an index of 0, the second value has an index of 1, and so on. So to access the first value in our roadTrip array, we would use the following code:

let firstStop = roadTrip[0];

This code will set the variable firstStop equal to the value "Darjeeling", since that is the first value in our roadTrip array.

Let’s now explore how we can use array methods to modify, delete, add, and perform a variety of other actions.

1. concat() :

Do you have two or more arrays that you want to combine into one? Use the concat() method!

  • The concat() method in JavaScript is used to join two or more arrays to create a new array that contains all the elements of the original arrays.
  • The concat() method does not modify the original arrays, instead it returns a new array that contains the combined elements of the original arrays.
const myArray = [1, 2, 3];
const anotherArray = [4, 5, 6];

const combinedArray = myArray.concat(anotherArray);
console.log(combinedArray);

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

2. every() :

Need to check if all elements in an array pass a test? Use the every() method!

  • The every() method in JavaScript is used to check if every element in an array satisfies a particular condition.
  • It returns a Boolean value (true or false) based on the result of the condition.
let numbers = [12, 15, 18, 20];

let result = numbers.every(number => number > 10);

console.log(result);

// Output: true

3. fill() :

Want to fill an array with a specific value? Use the fill() method!

  • The fill() method in JavaScript is used to fill all the elements of an array with a some value.
  • It takes one or two arguments - the value to be used for filling and an optional start and end index specifying the range of elements to be filled.
  • You can also specify a range of elements to be filled using the optional start and end index arguments. Here’s an example:
  • ex 1-
let arr = [1, 2, 3, 4, 5];
arr.fill(0);
console.log(arr);

// Output: [0, 0, 0, 0, 0]
  • ex2-
let arr = [1, 2, 3, 4, 5];
arr.fill(0, 1, 3);
console.log(arr);

// Output: [1, 0, 0, 4, 5]
  • In this example, the fill() method is used to fill only the elements at indices 1 and 2 with the value 0, leaving the other elements unchanged. The second argument 1 specifies the starting index and the third argument 3 specifies the ending index (exclusive).

That’s it! The fill() method is a simple and useful tool for quickly filling arrays with a default value.

4. filter() :

Need to create a new array with only certain elements from another array? Use the filter() method!

  • The filter() method is a built-in array method that allows you to create a new array with all elements that pass a certain condition.
  • It takes in a callback function that returns a boolean value, and creates a new array with all elements that return true when passed through the callback function.

Here’s an example:

let arr = [1, 2, 3, 4, 5, 6];

let evenNumbers = arr.filter(function(num) {
return num % 2 === 0;
});

console.log(evenNumbers);

// Output: [2, 4, 6]
  • In this example, we have an array arr with the numbers 1 through 6. We then use the filter() method to create a new array called evenNumbers that contains only the even numbers from the original array.
  • The callback function we passed to the filter() method checks whether each element in the array is even by using the modulus operator % to check if the remainder of the element divided by 2 is 0. If the remainder is 0, the callback function returns true, indicating that the element should be included in the new array. If the remainder is not 0, the callback function returns false, indicating that the element should be excluded from the new array.
  • So in this example, the evenNumbers array contains only the even numbers from the original arr array, which are 2, 4, and 6. The filter() method has effectively filtered out all of the odd numbers from the original array.

5. find() :

Want to find the first element in an array that satisfies a certain condition? Use the find() method!

  • The find() method in JavaScript is a built-in array method that returns the value of the first element in an array that satisfies a given condition or undefined if no such element is found..
  • It takes a callback function as its argument, which should return a boolean value.
let numbers = [1, 2, 3, 4, 5];

let evenNumber = numbers.find(num => num % 2 === 0);

console.log(evenNumber);

// Output: 2
  • In this example, we have an array called numbers which contains five elements. We want to find the first even number in this array. So, we use the find() method along with an arrow function as the condition. The arrow function takes a parameter num and returns true if num is even.
  • The find() method returns the first even number found in the array, which is 2. Finally, we print the result to the console using the console.log() method.

6. findIndex() :

Need to find the index of the first element in an array that satisfies a certain condition? Use the findIndex() method!

  • findIndex() is a method in JavaScript that returns the index of the first element in an array that passes a given test function. If no element passes the test, it returns -1.
  • Here is an example to demonstrate how findIndex() works:
const ages = [18, 21, 16, 25, 20];

const adultIndex = ages.findIndex(age => age >= 18);

console.log(adultIndex);

// Output: 0
  • In this example, we have an array of ages. We use the findIndex() method to find the index of the first element that is greater than or equal to 18. Since the first element (18) meets this condition, the method returns its index, which is 0.
  • We can also pass a function to findIndex() that defines our own custom test. For example:
let numbers = [10, 20, 30, 40, 50];

function checkNumber(number) {
return number > 25;
}

let index = numbers.findIndex(checkNumber);

console.log(index); // Output: 2
  • The findIndex() method searches through an array and returns the index of the first element that passes a test function. In the example, the test function checks if a number is greater than 25. It returns the index of the element with value 30 (which is 2), since it's the first number greater than 25. If no element passes the test, it returns -1.

7. flat() :

Have a nested array and need to flatten it? Use the flat() method!

  • The flat() method is a built-in method in JavaScript arrays that creates a new flattened array by concatenating sub-arrays of a given array.
  • Note that the flat() method can also take an optional argument that specifies the depth of flattening. For example, if we want to flatten only one level of sub-arrays, we can pass an argument of 1 to the flat() method like this:
let numbers = [1, 2, [3, [4]], 5, [6]];

let flattenedNumbers = numbers.flat(1);

console.log(flattenedNumbers);

// Output: [1, 2, 3, [4], 5, 6]
  • In this example, we have a nested sub-array [3, [4]] in the numbers array. We pass an argument of 1 to the flat() method which flattens only one level of sub-arrays. Therefore, the new array flattenedNumbers contains the first level of sub-arrays flattened while the nested sub-array [4] remains intact.

8. forEach() :

Want to execute a function for each element in an array? Use the forEach() method!

  • The forEach() method is a built-in method in JavaScript arrays that allows us to loop through each element of an array and perform a function on each element.
let fruits = ['apple', 'banana', 'mango'];

fruits.forEach(function(fruit) {
console.log(fruit);
});

// Output:
// apple
// banana
// mango
  • In this example, we have an array of fruits, and we call the forEach() method on the fruits array with a function that takes a fruit parameter. The forEach() method loops through each element of the array and calls the function on each element. In this case, the function simply logs the fruit parameter to the console.
  • Note that the forEach() method does not return anything. Its purpose is simply to loop through the array and execute the provided function for each element.

9. includes() :

Need to check if an element exists in an array? Use the includes() method!

  • The includes() method is a built-in method in JavaScript arrays that checks whether an array includes a certain element or not, and returns a boolean value of true or false.
let fruits = ['apple', 'banana', 'orange'];

let includesApple = fruits.includes('apple');
let includesMango = fruits.includes('mango');

console.log(includesApple); // Output: true
console.log(includesMango); // Output: false
  • In this example, we have an array of fruits and we check whether the array includes the elements ‘apple’ and ‘mango’. We call the includes() method on the fruits array with the values 'apple' and 'mango' as its arguments. The includes() method returns true if the array includes the element and false if it does not.
  • In this case, the includes() method returns true for the element 'apple' since it exists in the fruits array, and false for the element 'mango' since it does not exist in the fruits array.

10. indexOf() :

Want to find the index of a specific element in an array? Use the indexOf() method!

  • The indexOf() method is a built-in method in JavaScript arrays that returns the first index at which a given element can be found in an array, or -1 if it is not present.
let fruits = ['apple', 'banana', 'orange'];

let index = fruits.indexOf('banana');

console.log(index); // Output: 1
  • In this example, we have an array of fruits and we call the indexOf() method on the fruits array with the argument 'banana'.
  • The indexOf() method will loop through each element of the array until it finds the element we are looking for. In this case, the element 'banana' is found at index 1, so the indexOf() method returns 1.
  • Note that if the element we are looking for is not present in the array, the indexOf() method returns -1.

11. join() :

Need to join all elements in an array into a string? Use the join() method!

  • The join() method is a built-in method in JavaScript arrays that joins all the elements of an array into a string.
  • You can specify a separator to use between each element when they are joined together.
let fruits = ['apple', 'banana', 'orange'];

let result = fruits.join(', ');

console.log(result); // Output: "apple, banana, orange"
  • In this example, we have an array of fruits. We call the join() method on the fruits array with ', ' as the separator to use between each fruit. The join() method joins all the elements of the array into a string with the specified separator and returns the result.
  • You can use any separator you like, or omit it altogether to join the elements without any separator.

Phew! That was a lot of array methods to learn, but don’t worry — we’re not done yet! Just like how there are more toppings to add to your pizza, there are more array methods to add to your coding arsenal. And I’m here to guide you through it all, so don’t stress out. So let’s put on our coding hats and continue on this array adventure together!

12. map() :

Need to create a new array by manipulating each element in another array? Use the map() method!

  • The map() method is a built-in method in JavaScript arrays that allows you to create a new array by applying a function to each element of an existing array.
  • The new array will have the same length as the original array, but with each element transformed by the provided function.
const names = ["Alice", "Bob", "Charlie"];

const nameLengths = names.map((name) => {
return name.length;
});

console.log(nameLengths);

// Output: [5, 3, 7]
  • In this example, we have an array of names and a function that returns the length of each name. We then call the map() method on the names array with the function as its argument.
  • The map() method will loop through each element of the array, apply the function to it, and return a new array with the transformed values. In this case, the map() method creates a new array called nameLengths with the length of each name in the original names array.
  • Note that the map() method does not modify the original array - it returns a new array with the transformed values.

13. pop() :

Want to remove the last element of an array and return it? Use the pop() method!

  • The pop() method is a built-in method in JavaScript arrays that removes the last element from an array and returns it.
  • Here’s an example:
let fruits = ['apple', 'banana', 'orange'];

let lastFruit = fruits.pop();

console.log(lastFruit); // Output: 'orange'

console.log(fruits); // Output: ['apple', 'banana']
  • In this example, we have an array of fruits, and we call the pop() method on it. The pop() method removes the last element from the array (which is 'orange') and returns it. We then assign the returned value to the variable lastFruit. Finally, we log both lastFruit and fruits arrays to the console to see the result.
  • Note that the pop() method modifies the original array and reduces its length by one.

14. push() :

Want to add one or more elements to the end of an array? Use the push() method!

  • The push() method is a built-in method in JavaScript arrays that adds one or more elements to the end of an array and returns the new length of the array.
  • Here’s an example:
let fruits = ["apple", "banana", "orange"];
let newLength = fruits.push("grape");

console.log(fruits); // Output: ["apple", "banana", "orange", "grape"]
console.log(newLength); // Output: 4
  • In this example, we have an array of fruits and we call the push() method on it with the argument "grape". The push() method adds "grape" to the end of the fruits array and returns the new length of the array, which is 4. We then log the fruits array and the new length to the console.
  • You can also use the push() method to add multiple elements to an array at once, like this:
let animals = ["dog", "cat"];
let newLength = animals.push("bird", "hamster");

console.log(animals); // Output: ["dog", "cat", "bird", "hamster"]
console.log(newLength); // Output: 4
  • In this example, we add two elements, "bird" and "hamster", to the animals array using the push() method, and the new length of the array is again 4.

14. reduce() :

Need to reduce all elements in an array into a single value? Use the reduce() method!

  • The reduce() method is a powerful built-in method in JavaScript arrays that allows us to iterate through an array and accumulate a single value based on the elements of the array.
let numbers = [1, 2, 3, 4, 5];

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

console.log(sum); // Output: 15
  • In this example, we have an array of numbers and we want to calculate the sum of all the numbers. We call the reduce() method on the numbers array and pass it a function that takes two arguments: an accumulator and a currentValue.
  • The accumulator is a value that accumulates the result of the function as it loops through the array. The currentValue is the current element being processed by the function.
  • The reduce() method loops through each element of the array and applies the function to the accumulator and currentValue arguments. In this case, we start with an initial accumulator value of 0 and add each element of the array to it until we have the final sum of all the elements.
  • Finally, the reduce() method returns the accumulated value (in this case, the sum of all the numbers in the array).
  • Note that the reduce() method can be used to perform a variety of operations on an array, not just summing. It's a very flexible method that can be adapted to many use cases.

15. reverse() :

Want to reverse the order of elements in an array? Use the reverse() method!

  • The reverse() method is a built-in method in JavaScript arrays that reverses the order of the elements in an array. The first element becomes the last, and the last element becomes the first.
  • Here’s an example:
let numbers = [1, 2, 3, 4, 5];
numbers.reverse();
console.log(numbers); // Output: [5, 4, 3, 2, 1]
  • In this example, we have an array of numbers, and we call the reverse() method on it. The reverse() method will modify the original array by reversing the order of its elements.
  • Note that the reverse() method modifies the original array, rather than creating a new array.
  • If you want to create a new array with the elements in reverse order, you can use the slice() method to create a copy of the original array and then call the reverse() method on the new array.
  • For example:
let numbers = [1, 2, 3, 4, 5];
let reversedNumbers = numbers.slice().reverse();

console.log(reversedNumbers); // Output: [5, 4, 3, 2, 1]
console.log(numbers); // Output: [1, 2, 3, 4, 5]
  • In this example, we use the slice() method to create a copy of the original array (numbers) and then call the reverse() method on the new array (reversedNumbers). The reverse() method will reverse the order of the elements in the new array without modifying the original array.

16. shift() :

Want to remove the first element of an array and return it? Use the shift() method!

  • The shift() method removes the first element from an array and returns it. This method changes the original array and shifts all the remaining elements one position to the left.
let numbers = [1, 2, 3, 4, 5];

let shiftedNumber = numbers.shift();

console.log(shiftedNumber); // Output: 1
console.log(numbers); // Output: [2, 3, 4, 5]
  • In this example, we have an array of numbers. We then call the shift() method on the numbers array. The shift() method removes the first element (which is 1 in this case) and returns it. We store the returned value in the variable shiftedNumber.
  • The shift() method also modifies the original numbers array by shifting all the remaining elements one position to the left. Therefore, the numbers array now contains [2, 3, 4, 5].
  • Note that if the array is empty, the shift() method returns undefined.

17. slice() :

Need to create a new array from a portion of an existing array? Use the slice() method!

  • The slice() method creates a new array by extracting a portion of an existing array.
  • Here’s an example:
let fruits = ['apple', 'banana', 'orange', 'kiwi', 'mango'];

let citrusFruits = fruits.slice(2, 4);

console.log(citrusFruits); // Output: ['orange', 'kiwi']
  • In this example, we have an array of fruits. We call the slice() method on the fruits array with two arguments: the starting index (inclusive) and the ending index (exclusive) of the portion we want to extract.
  • In this case, the starting index is 2 (which corresponds to the element 'orange') and the ending index is 4 (which corresponds to the element 'mango', but this element is excluded from the new array).
  • Therefore, the slice() method returns a new array containing the elements 'orange' and 'kiwi', which are the elements at indices 2 and 3 in the original array.
  • Note that if the starting index is greater than or equal to the length of the array, the slice() method returns an empty array. If the ending index is omitted, the slice() method extracts all the elements from the starting index to the end of the array.

18. some() :

Want to check if at least one element in an array satisfies a condition? Use the some() method!

  • The some() method is a built-in method in JavaScript arrays that tests whether at least one element in the array passes a test function. The method returns true if the test function returns true for at least one element in the array, otherwise it returns false.
  • Here’s an example:
let numbers = [10, 20, 30, 40, 50];

function checkNumber(number) {
return number > 25;
}

let result = numbers.some(checkNumber);

console.log(result); // Output: true
  • In this example, we have an array of numbers and a function checkNumber() that returns true if the number is greater than 25. We then call the some() method on the numbers array with the checkNumber() function as its argument.
  • The some() method will loop through each element of the array and call the checkNumber() function on each element until it finds an element that returns true. In this case, the checkNumber() function returns true for the element with value 30. Therefore, the some() method returns true.
  • Note that if none of the elements in the array satisfy the condition in the test function, the some() method returns false.

19. sort() :

Need to sort the elements in an array? Use the sort() method!

  • The sort() method in JavaScript is a built-in method that sorts the elements of an array in place and returns the sorted array. By default, the sort() method sorts the array elements in alphabetical order.
  • Here’s an example:
let fruits = ['banana', 'apple', 'orange', 'grape'];

fruits.sort();

console.log(fruits); // Output: ['apple', 'banana', 'grape', 'orange']
  • In this example, we have an array of fruits, and we call the sort() method on the fruits array. The sort() method sorts the elements of the array in alphabetical order and returns the sorted array.
  • You can also sort numeric arrays using the sort() method, let’s see how it works with numeric arrays.
  • As we know sort() method can be used to sort elements of an array in ascending order based on Unicode character code values by default.
  • Before we explore how it sorts based on Unicode character code values, let’s see some examples.
let numArray = [3, 4, 1, 7, 2];
let sortedArr = numArray.sort();
console.log(sortedArr);

// Output: [1,2,3,4,7]
  • It is also important for you to know that when you apply the sort() method to an array, it will change the position of the elements in the original array. This means you do not need to assign a new variable to the sorted array:
  • The sort() method compares the elements of the array by converting them into strings and then comparing their Unicode code points. This means that in some situations, the sorting could go wrong in reality:
let numArray = [3, 10, 4, 21, 5, 2].sort();
console.log(numArray);

// Output: [10, 2, 21, 3, 4, 5]

Going out of your head, isn’t it? Sorting numbers can be confusing, but don’t worry, we’ll see how to correctly sort a number array in JavaScript!

  • In the example where 3, 10, 4, 21, 5, 2 are sorted as 10, 2, 21, 3, 4, 5 instead of 2, 3, 4, 5, 10, 21.
  • To solve this shortcoming, you can provide a comparison function that defines the desired sorting order.
  • For sorting an array of numbers, the comparison function should subtract the second number from the first number.
  • This will result in a negative number if the first number is smaller than the second number, a positive number if the first number is larger than the second number, and 0 if the two numbers are equal.
  • Here’s an example:
let numbers = [10, 5, 20, 25];

numbers.sort(function(a, b) {
return a - b;
});

console.log(numbers); // Output: [5, 10, 20, 25]
  • In this example, we have an array of numbers, and we provide a compare function to the sort() method as an argument. The compare function compares two numbers, a and b, and returns a negative value if a is less than b, a positive value if a is greater than b, and zero if a is equal to b.
  • By using this compare function, the sort() method sorts the numbers in ascending order and returns the sorted array.
  • To sort the array in descending order, you can simply switch the positions of a and b in the compare function.
  • Here’s an example:
let numbers = [10, 5, 20, 25];

numbers.sort(function(a, b) {
return b - a;
});

console.log(numbers); // Output: [25, 20, 10, 5]
  • In this example, we provide a different compare function to the sort() method that sorts the numbers in descending order.
  • Note that the sort() method modifies the original array in place, so the original array will be sorted after calling the sort() method.

20. splice() :

Want to add or remove elements from an array at a specific position? Use the splice() method!

  • The splice() method in JavaScript is a built-in method that changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
  • The splice() method takes two or more arguments: the starting index, the number of elements to remove (optional), and the elements to add (optional).
let fruits = ['apple', 'banana', 'orange'];

fruits.splice(1, 1, 'grape', 'kiwi');

console.log(fruits); // Output: ['apple', 'grape', 'kiwi', 'orange']
  • In this example, we have an array of fruits, and we call the splice() method on the fruits array. We pass three arguments to the splice() method: the starting index 1, the number of elements to remove 1 (which removes the element at index 1, which is 'banana'), and the elements to add 'grape' and 'kiwi'. The splice() method then removes 'banana' and adds 'grape' and 'kiwi' in their place, resulting in a modified array with the values ['apple', 'grape', 'kiwi', 'orange'].
  • Note that the splice() method modifies the original array in place, so the original array will be changed after calling the splice() method.

21. toString() :

Want to convert an array to a string? Use the toString() method!

  • The toString() method in JavaScript is a built-in method that converts an array into a string and returns the resulting string.
  • Here’s an example:
let fruits = ['apple', 'banana', 'orange', 'grape'];

let result = fruits.toString();

console.log(result); // Output: "apple,banana,orange,grape"
  • In this example, we have an array of fruits, and we call the toString() method on the fruits array. The toString() method converts the array into a string, separating each element with a comma, and returns the resulting string.
  • You can also use the toString() method to convert other data types into strings.

22. unshift() :

Want to add one or more elements to the beginning of an array? Use the unshift() method!

  • The unshift() method in JavaScript is a built-in method that adds one or more elements to the beginning of an array and returns the new length of the array.
  • Here’s an example:
let fruits = ['banana', 'apple', 'orange'];

fruits.unshift('grape');

console.log(fruits); // Output: ['grape', 'banana', 'apple', 'orange']
  • In this example, we have an array of fruits, and we call the unshift() method to add the string 'grape' to the beginning of the fruits array. The unshift() method modifies the original array and returns the new length of the array, which is 4 in this case.
  • You can also add multiple elements to the beginning of an array by passing them as separate arguments to the unshift() method.
let numbers = [3, 4, 5];

numbers.unshift(1, 2);

console.log(numbers); // Output: [1, 2, 3, 4, 5]
  • In this example, we have an array of numbers, and we call the unshift() method to add the numbers 1 and 2 to the beginning of the numbers array. The unshift() method modifies the original array and returns the new length of the array, which is 5 in this case.

And so, we’ve reached the end of our journey exploring the wild and wonderful world of JavaScript array methods. It’s been quite the adventure, but I hope you’ve learned some cool tricks to level up your coding game.

From concatenating arrays to filtering out specific elements, we’ve covered a lot of ground. These array methods may seem like a small part of JavaScript, but they are powerful tools that can save you time and simplify your code. With these methods in your toolbelt, you’re well on your way to becoming a JavaScript ninja. So go forth and keep on arrayin’!

Happy Coding!

--

--

Ashwini Paraye
Ashwini Paraye

Written by Ashwini Paraye

👨‍💻Tech enthusiast & writer📚 Simplifying coding concepts & sharing tips to make tech fun & accessible. Your support fuels my passion—let’s grow together!🚀

No responses yet