Using the find array helper in ES6
July 19, 2017 Leave a comment
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.