javascript array helper - find

Javascript Array Helper: find()

The purpose of the find() array helper is to execute a function for every array element and return a the first array occurrence which matches your specified condition.

A Practical Example

Suppose we have an array of products and we want to find the first product with a category of “books”.

First, let’s look at how we would do this in older ES5 javascript.

var products = [
   { name: 'Checkers', category: 'Toys'},
   { name: 'Harry Potter', category: 'Books'},
   { name: 'iPhone', category: 'Electronics'},
   { name: 'Learn PHP', category: 'Books'}
];
var product;

for (var i=0; i<products.length; i++) {
   if (products[i].category === 'Books') {
      product = products[i];
      break;
   }
}
console.log(product);

Javascript find() Helper

Here is how the example above would be re-written using the find helper.

var products = [
    { name: 'Checkers', category: 'Toys'},
    { name: 'Harry Potter', category: 'Books'},
    { name: 'iPhone', category: 'Electronics'},
    { name: 'Learn PHP', category: 'Books'}
];
var product;

product = products.find(function(product) {
    return product.category === 'Books';
});
console.log(product);

The way this works is that for each array element, a callback function will get called, where you can test a condition and return true or false.

If you return true then that element will be returned and all further iterations will stop.

As you can see, using the find helper function simplifies and reduces the amount of code you need to write.

Hope this helps, in my next post I will discuss if the array .reduce function.

Leave a Reply

Your email address will not be published.