Finding elements in arrays with ES6

November 13, 2018

In this article, I’ll teach you how to find both one and every matching element in an array. JavaScript employs two methods for these in particular: find (for one) and filter (for all). Let’s get started.

Find the first matching element

Find the first matching element in a JavaScript array with find. Let’s say we have a group of records and we want to retrieve the first with a Lifetime plan:

// Records you want to search
const members = [
	{ plan: 'Monthly',  username: 'mona' },
	{ plan: 'Lifetime', username: 'queen' },
	{ plan: 'Lifetime', username: 'fox' }
]

// How to use `find` to search them
members.find(lifetimeMembers) // { plan: 'Lifetime', username: 'queen' }
function lifetimeMembers(record) {
	return record.plan === 'Lifetime'
}

You can also shorten find with an arrow function:

// find first `Lifetime` record in `members` array
members.find(record => record.plan === 'Lifetime')

Find all matching elements

Now, what if you want to retrieve all matching elements? Then you can use filter in the place of find:

// The same array from last time
const members = [
	{ plan: 'Monthly',  username: 'mona' },
	{ plan: 'Lifetime', username: 'queen' },
	{ plan: 'Lifetime', username: 'fox' }
]

// Using `filter` to return ALL matches
members.filter(lifetimeMembers) // [{ plan: 'Lifetime', username: 'queen' }, { plan: 'Lifetime', username: 'fox' }]
function lifetimeMembers(record) {
	return record.plan === 'Lifetime'
}

And we can clean this up with ES6 like so:

// find every `Lifetime` record in `members` array
members.filter(record => record.plan === 'Lifetime')

And that’s all there is to it. While you’re doing array manipulation, you may also be interested in returning all unique values from an array. If that’s the case, I have a pretty cool one-liner for that.