JavaScript Higher-Order Array Methods

A number of higher-order array methods were introduced into the JavaScript language with the release of ES6. These methods have helped to shape the way that we work with frameworks like React, making it much easier to manipulate data in arrays.

As we work on various problems it’s easy to forget about some of these handy tools that can make our lives a lot easier. This post is intended to be a quick reference guide for anyone working day-to-day with modern JavaScript in order to find the right method for the job at hand.

One of the great things to mention is that these methods can be chained together to carry out any number of actions one after another.

While I (highly) recommend getting to grips with the theory behind these techniques and knowing why something works, this serves as more of an at-a-glance guide for the times when you can’t quite remember what the darn method is called that does that awesome thing that you could really use right now. For a more detailed overview of each API, I’ve included a link to the relevant MDN doc.

forEach()

The forEach() method enables us to iterate over every item in an array and execute a provided function on every single iteration.

Here’s a traditional for loop for comparison:

for (let i = 0; i < companies.length; i++) {
  console.log(companies[i])
}

Here is the forEach() equivalent:

const companies = [
    {
        name: ‘Apple’,
        est: ‘1977’
    },
    {
        name: ‘Facebook’,
        est: ‘2004’
    },
    {
        name: ‘Google’,
        est: ‘1998’
    },
    {
        name: ‘Microsoft’
        est: '1975’
    }
];

companies.forEach(function(company) {
    console.log(company);
});

companies.forEach(function(company) {
    console.log(company.name);
});

forEach MDN documentation

filter()

The filter() method filters items out from an array and returns a new array.

Here’s an example with a for loop where we would first need to initialise an empty array:

let canDrink = []

for (let i = 0; i < ages.length; i++) {
  if (ages[i] >= 21) {
    canDrink.push(ages[i])
  }
}

console.log(canDrink)

Using filter() we can store the returned array directly in a variable. The following example passes in a function that features an if statement:

const canDrink = ages.filter(function(age) {
  if (age >= 21) {
    return true
  }
})

console.log(canDrink)

We can make this more elegant by using an arrow function to produce a single line of code:

const canDrink = ages.filter(age => age >= 21)

console.log(canDrink)

Here is another example where we can filter from an array of objects:

const retailCompanies = companies.filter(function(company) {
  if (company.category === "Retail") {
    return true
  }
})

console.log(retailCompanies)

Again, using an arrow function:

const retailCompanies = companies.filter(
  company => company.category === "Retail"
)

console.log(retailCompanies)

filter MDN documentation

map()

The map() method enables us to perform an action on every item in an array and return a new array with the results.

As with the previous methods, we can pass in an anonymous function and create a block of logic:

const testMap = companies.map(function(company) {
  return `${company.name} [${company.start} - ${company.end}]`
})

console.log(testMap)

We can also use an arrow function:

const testMap = companies.map(
  company => `${company.name} [${company.start} - ${company.end}]`
)

Here’s another example in a different scenario:

const agesSquare = ages.map(age => Math.sqrt(age));
const agesTimesTwo = ages.map(age => age \* 2);

console.log(agesSquare);
console.log(agesTimesTwo);

We can also combine multiple maps:

const agesCalc = ages
.map(age => Math.sqrt(age))
.map(age => age \* 2);

console.log(agesCalc);

map MDN documentation

sort()

The sort() method allows us to compare values in an array and move them up and down in the array order depending on a condition, returning 1 (true) or -1 (false).

Initially sort() can be a little tricky to understand, so we’ll start with a more traditional if statement to illustrate how it works.

Let’s sort an array of companies by the year they began:

const sortedCompanies = companies.sort(function(c1, c2) {
  if (c1.start > c2.start) {
    return 1
  } else {
    return -1
  }
})

console.log(sortedCompanies)

Now let’s use an arrow function with a ternary conditional:

const sortedCompanies = companies.sort((a, b) => (a.start > b.start ? 1 : -1))

console.log(sortedCompanies)

In another example, we can sort ages lowest to highest:

const sortAges = ages.sort((a, b) => a - b)

console.log(sortAges)

To sort ages highest to lowest, we can simply flip the a and b values:

const sortAges = ages.sort((a, b) => b - a)

console.log(sortAges)

sort MDN documentation

reduce()

reduce() takes in a reducer function (that we can create) and applies it to every element in the array, returning a single value. In other words, it can take an array of elements, process them by some condition/action, and reduce them down to one value.

A common example is to sum iterations of an array. Let’s take a look at the traditional approach using a for loop:

let ageSum = 0

for (let i = 0; i < ages.length; i++) {
  ageSum += ages[i]
}

console.log(ageSum)

With reduce() we can pass in an anonymous function with the value that we want to increment (total) and each iteration (age):

const ageSum = ages.reduce(function(total, age) {
  return total + age
}, 0) // Takes a starting count (in this case 0)

Note that we also need to initialise a starting value, which reduce() takes as a second parameter.

We can slim this down with an arrow function:

const ageSum = ages.reduce((total, age) => total + age, 0)

Here’s a slightly more complex example where we calculate the total ranges for company lifespans:

const totalYears = companies.reduce(function(total, company) {
  return total + (company.end - company.start)
}, 0)

console.log(totalYears)

Again, with an arrow function:

const totalYears = companies.reduce(
  (total, company) => total + (company.end - company.start),
  0
)

console.log(totalYears)

reduce MDN documentation

find()

The find() method will return the first element that matches a provided condition. It’s important to note that it will stop iterating once it finds this first element.

We can therefore search for a matching object in an array, for example:

const items = [
  { name: 'Bike', price: 100 },
  { name: 'Book', price: 5 },
  { name: 'Album', price: 10 }
]

const foundItem = items.find(item => {
  return item.name === ‘Book';
})

console.log(foundItem);

This will return the very first item that it finds in the array that returns true for the statement that we pass inside of the find() function.

The arrow function equivalent would be as follows:

const foundItem = items.find(item => item.name === ‘Book’);

find MDN documentation

some()

some() will check array elements for a condition and return true if any items meet that condition.

const items = [
  { name: 'Bike', price: 100 },
  { name: 'TV', price: 200 },
  { name: 'Album', price: 10 },
  { name: 'Book', price: 5 },
  { name: 'Phone', price: 500 },
  { name: 'Computer', price: 1000 },
  { name: 'Keyboard', price: 25 }
]

const hasInexpensiveItems = items.some(item => {
  return item.price <= 100;
}

console.log(hasInexpensiveItems);
// true

Again we can slim this down:

const hasInexpensiveItem = items.some(item => item.price <= 100)

some MDN documentation

every()

The every() method is similar to some(), only it will test an array for a condition and returns true if all items meet the condition.

const items = [
  { name: 'Bike', price: 100 },
  { name: 'TV', price: 200 },
  { name: 'Album', price: 10 },
  { name: 'Book', price: 5 },
  { name: 'Phone', price: 500 },
  { name: 'Computer', price: 1000 },
  { name: 'Keyboard', price: 25 }
]

const hasInexpensiveItems = items.every(item => {
  return item.price <= 1000;
}

console.log(hasInexpensiveItems);
// true
const hasInexpensiveItem = items.every(item => item.price <= 1000)

every MDN documentation

includes()

The includes() method will determine whether or not an array includes a certain value among its entries, returning true or false as appropriate.

const array1 = [1, 2, 3]

console.log(array1.includes(2))
// expected output: true

const pets = ["cat", "dog", "bat"]

console.log(pets.includes("cat"))
// expected output: true

console.log(pets.includes("at"))
// expected output: false

includes MDN documentation