How to easily find array elements in JavaScript

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: 'joker' }
]

// 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: 'joker' }
]

// Using `filter` to return ALL matches
members.filter(lifetimeMembers) // [{ plan: 'Lifetime', username: 'queen' }, { plan: 'Lifetime', username: 'joker' }]
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.

About the author

I'm Mark Thomas Miller, a full stack engineer and designer currently working at ConvertKit. (We're hiring!) People like Arnold Schwarzenegger, Lindsey Stirling, and Tim Ferriss use features I've built to connect with their fans. I'm currently geeking out about Svelte, mechanical keyboards, and minimalist UI design, and replaying Ocarina of Time.