8 Must Know JavaScript Array Methods

7 min read

In this tutorial, we’ll be covering eight JavaScript array methods that will significantly simplify your coding experience. These array methods are filter(), map(), find(), forEach(), some(), every(), reduce(), includes().

We will look at each of these in detail, and to illustrate these methods, we’ll be using an array of items.

1. Filter Method

The filter method allows you to create a new array that includes items that pass a certain condition.

Let’s say we have an array of employees and we want to get all employees whose age is less than or equal to 30. Here’s how we can do it:

JavaScript
const employees = [
    { name: "Carl", age: 35 },
    { name: "John", age: 27 },
    { name: "Sara", age: 25 },
    { name: "Diana", age: 31 },
    { name: "Peter", age: 32 },
    { name: "Charles", age: 26 },
];

const filteredEmployees = employee.filter(employee => employee.age <= 30);
console.log(filteredEmployees);

This filter method employs a single function with one parameter labeled ’employee’, which represents each element within the array. This function is required to return a boolean value based on a conditional check, dictating whether the item will be included in the new array. The logic for this specific use case is articulated by the statement “employee.age <= 30“, which means all employees with age value equal to 30 or less will be included in the new ‘filteredEmployees‘ array.

The simplicity and ease of use of the filter method make it an essential tool in JavaScript programming. It operates by returning either ‘true’ or ‘false’ for each item; items that return ‘true’ find a place in the new array, while those returning ‘false’ do not.

The filter method does not alter the original array. If we log the original employees array, you’ll find it remains intact, while filteredEmployees includes only those items that meet our specified condition.

2. Map Method

The map method creates a new array by applying a function to all items in the original array.

Let’s say we want to create a new array that contains only the names of our employees:

JavaScript
const employees = [
    { name: "Carl", age: 35 },
    { name: "John", age: 27 },
    { name: "Sara", age: 25 },
    { name: "Diana", age: 31 },
    { name: "Peter", age: 32 },
    { name: "Charles", age: 26 },
];

const employeeNames = employees.map(employee => employee.name);
console.log(employeeNames);

Here, we have a parameter named “employee”. For each item in the “employees” array, we are returning the property name for each employee.

If we wanted the ages instead of the names, we would simply replace employee.name with employee.age.

The map method is an incredibly handy tool, particularly when you need to extract a specific attribute, like names, from an object or transform one array into another. As you delve deeper into programming, you’ll often find yourself opting for the map method over conventional loops or alternative techniques due to its efficiency and simplicity.

3. Find Method

The find method returns the first item in an array that satisfies a certain condition. This condition is typically formulated as a true or false statement

Let’s say we want to find an employee named ‘John’:

JavaScript
const employees = [
    { name: "Carl", age: 35 },
    { name: "John", age: 27 },
    { name: "Sara", age: 25 },
    { name: "Diana", age: 31 },
    { name: "Peter", age: 32 },
    { name: "Charles", age: 26 },
];

const foundEmployee = employees.find(employee => employee.name === 'John');
console.log(foundEmployee); //logs { name: "John", age: 27 }

As we wanted to retrieve an employee named ‘John’ from the employees array, we used the statement employee.name == John'. Upon execution, the method will return the item in the array that contains the property name: "John".

The same procedure can be applied to any attribute. If we replace ‘John’ with ‘Sara’, it will return the first item named ‘Sara’ in the array. It’s worth noting that the ‘find‘ method will only return the very first item that meets the given condition.

Boost Your Business

Want more clients and sales? Our web development services will optimize your website to convert more visitors into customers.

Get Started Today

4. ForEach Method

The forEach method executes a provided function once for each array item. Unlike the previous methods, it doesn’t return anything.

If we want to print the name of each item of an array, we would do the following:

JavaScript
const employees = [
    { name: "Carl", age: 35 },
    { name: "John", age: 27 },
    { name: "Sara", age: 25 },
];

employees.forEach(employee => console.log(employee.name));

We are printing out the name of each employee in the array. The function will execute for every item in the array, resulting in the names of all employees being printed. We could print other attributes, or execute any operation required for each element in the array.

The forEach method operates much like a traditional ‘for‘ loop, but with a functional twist. It accepts a function as an argument, which is executed for each item in the array.

The beauty of the forEach method lies in its simplicity and elegance when working with arrays. It eliminates the need for writing out the traditionally lengthy syntax of a ‘for‘ loop. This makes it a preferred choice for scenarios where you need to loop over and perform operations on each element of an array.

5. Some Method

The some method checks if at least one item in an array meets a certain condition, and returns true if so. It deviates somewhat from the other methods we’ve previously discussed as it doesn’t produce a new array; rather, it returns a boolean value based on a specified condition.

To check if there are any employees with an age equals to 27 or less:

JavaScript
const employees = [
    { name: "Carl", age: 35 },
    { name: "John", age: 27 },
    { name: "Sara", age: 25 },
    { name: "Diana", age: 31 },
    { name: "Peter", age: 32 },
    { name: "Charles", age: 26 },
];

let hasYoungEmployees = employees.some(employee => employee.age <= 27);
console.log(hasYoungEmployees); //returns true

In our example, logging ‘hasYoungEmployees‘, you’ll find it returns ‘true’ as the array contains employees with ages below 27. However, if we alter our condition to check for ‘employee.age <= 20‘, the function would return ‘false’.

The syntax for the ‘some’ function mirrors those of other array methods, but its function is to evaluate the provided condition for each item in the array. If at least one item satisfies the condition, the ‘some‘ function will return ‘true’ for the entire array.

This powerful method provides a way to quickly check if any elements in an array meet a specific condition.

6. Every Method

The every method checks if all items in an array meet a certain condition, and returns true if they do.

To check if all employees have an age property less than 40:

JavaScript
const employees = [
    { name: "Carl", age: 35 },
    { name: "John", age: 27 },
    { name: "Sara", age: 25 },
    { name: "Diana", age: 31 },
    { name: "Peter", age: 32 },
    { name: "Charles", age: 26 },
];

const allYoung = employees.every(employee => employee.age <= 40);
console.log(allYoung); //logs true

Using the ‘every‘ function to check if all employees in the array are younger than 40, it will return ‘true’ only if all employees meet this criteria. However, if there are employees older than 40, the function will return ‘false’.

This method bears a resemblance to the ‘some‘ method, with a key difference in its operation. While the ‘some‘ method checks if at least one item in the array meets the condition, the ‘every‘ method verifies that all items in the array satisfy the specified condition.

This method is particularly handy when we need to verify that every element in an array satisfies a certain condition.

7. Reduce Method

The reduce() method is used to execute a given function on each item in an array, and reduce the array to a single value.

The ‘reduce’ method uses a different syntax. Instead of receiving just an item, it accepts an item and a property that represents the accumulating result. Let’s call this the ‘currentTotal‘, representing the total at each iteration. It also accepts a second argument, which serves as the initial point of our total. In this case, we want to start from zero.

To find the sum of the ages of all the employees:

JavaScript
const employees = [
    { name: "Carl", age: 35 },
    { name: "John", age: 27 },
    { name: "Sara", age: 25 },
    { name: "Diana", age: 31 },
    { name: "Peter", age: 32 },
    { name: "Charles", age: 26 },
];

const totalAge = employees.reduce((currentTotal, employee) => {currentTotal + employee.age}, 0);
console.log(totalAge); // logs 176

The function currentTotal + employee.age returns the sum of the current total and the age of the employee. For each item in the array, the ‘reduce‘ function executes, taking the accumulated total from the previous iteration as the ‘currentTotal‘.

At the first iteration, the ‘currentTotal‘ starts at zero (our second argument). So, for instance, when it encounters the first employee, ‘Carl’, it adds the age of ‘Carl’ to zero, returning 35. In the second iteration, the ‘current total’ is 35, and the new employee is ‘John’ (with an age of 27). The function now adds 27 to 35, making the ‘currentTotal‘ 62.

This process continues for all employees, adding each age to the ‘currentTotal‘, until it reaches the last employee. The total age of all employees is then stored in our ‘totalAge‘ variable, which can be logged or used further.

While ‘reduce’ may seem confusing at first, it’s incredibly handy when you need to perform cumulative operations on an array, such as calculating a total.

8. Includes Method

The includes method checks if an array includes a certain value, returning true or false. This method is unique as it does not take a function as an argument. Instead, it accepts a single value.

To check if an array includes the number 3:

JavaScript
const numbers = [1, 2, 3, 4, 5];
const includesThree = numbers.includes(3);
console.log(includesThree); //logs true

Here, we’re checking if this array includes the number 3, so we’re using the ‘includes‘ method, specifying 3 as the argument.

By doing this, ‘includes‘ will verify if the provided value (in our case, the number 3) exists within the array. Consequently, it will return ‘true‘ since our array indeed includes the number 3. However, if we were to change the argument to a number not present in the array, like 7, the method would return ‘false‘, signifying that the array does not include 7.

The ‘includes’ method is highly beneficial when you need to determine whether an array contains a specific value, particularly when dealing with simple arrays like one consisting of numbers. It bypasses the need for a complex ‘find‘ operation and makes the task straightforward.

Boost Your Business

Want more clients and sales? Our web development services will optimize your website to convert more visitors into customers.

Get Started Today
Profile image of author Jefferson Huera Guzman

Jefferson is the main author and administrator of Computernoobs.com. I like sharing information and news about technology.