Using the find array helper in ES6

ES6 comes with a number of helper methods that can be applied to arrays. One of these is called find which finds the first matching element in an array based on a condition. If you’re familiar with C# and LINQ then the find function is very similar to the Where/Select and FirstOrDefault LINQ extension methods.

Let’s see an example.

We have the following group of programmers:

let programmers = [
  	 {"name":"John","age":20,"language":"C#"},
     {"name":"Mary","age":24,"language":"Java"},
     {"name":"Jane","age":25,"language":"C++"},
     {"name":"Peter","age":22,"language":"JavaScript"},
     {"name":"Fred","age":21,"language":"C++"},
     {"name":"Sophie","age":28,"language":"C#"},
     {"name":"James","age":27,"language":"Java"},
     {"name":"Charlotte","age":26,"language":"Java"},
]

We want to find the first programmer whose name is Mary:

let mary = programmers.find(function(prog) {
  return prog.name === 'Mary'
})

Find accepts a function which in turn operates on a single member of the array which find is applied to. Filter iterates through each member in the array and calls the function that was provided to it. The function must return a value otherwise the result, “mary” in this case will be undefined. If the value of the argument “prog” fulfils the boolean condition in the find function then it is assigned to the variable “mary”. Note that only the first matching value is returned. Hence the find helper function is probably best suited for situations where you’re expecting find a single matching value. An example would be when searching for an object by ID.

The following function will return “Mary” even if there are multiple programmers whose language is Java:

let java = programmers.find(function(prog) {
  return prog.language === 'Java'
})

Mary is the first one with the programming language Java and the find function will break the loop after finding her.

View all posts related to JavaScript here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: