Javascript Array Callback Function Part 3 - FIND METHOD

The next part of the array methods we will be looking at that expects a callback is called 'FIND'. Find does what it sounds like. It finds, retrieves, and returns the value of the first element in the array that satisfies the provided testing function. Find returns only one value or element that matches in a given array even if they are several match, it stops after it finds the very first one.

FIND METHOD SYNTAX

- Using anynomous function statement

  arr.find(function (parameter) {
     return parameter;
})

- Using anynomous arrow function

  arr.find( parameter => {
     return parameter
})

Example 1: We have an array of Developer advocates. Let's find the first author with a 'dev' title.

let devAds = [
    'dev. Edidiong Asikpo',
    'dev. Bolaji Ayodeji',
    'dev. Erica Hanson',
    'dev. Stephen Counsellor'
]

// using an implicit return arrow function.

const findDev = devAds.find(devAd => (
    devAd.includes('dev.');
));
console.log(findDev)
OUTPUT
// 'dev. Edidiong Asikpo'

To figure out devAds contains the word dev. we use .includes method

the 'return' function have to return true or false, and first time it returns true for a given devAds array, find is done and it returns the first 'dev.'

EXAMPLE 3: Let's also see how find method works on objects using the same object we created in our last episode, but with an added key called 'rating'.

const books = [{
       title: 'Gods are not to blame',
       author: ['Ola Rotimi'],
       rating: 4.11
    },
    {
       title: 'Creating impressive proposals in Open Source Programs',
       author: ['Edidiong Asikpo'],
       rating: 4.36
    },
    {
       title: 'She inspires',
       author: ['Bolaji Ayodeji', 'Edidiong Asikpo'],
       rating: 4.15    
    },
    {
       title: 'javascript Grammer',
       author: ['javascript Teacher'],
       rating: 4.91
    }
];

const mostRated = books.find(book => book.rating >= 4.3);

console.log(mostRated)

//OUTPUT
{
 author: Array [ "Edidiong Asikpo" ]
 rating: 4.36
 title: "Creating impressive proposals in Open Source Programs"
}
// Lets find the book authored by Edidiong
const didicodes = books.find(book => (
    book.author.includes('Edidiong Asikpo')
))

console.log(didicodes)
//OUTPUT
{
 author: Array [ "Edidiong Asikpo" ]
 rating: 4.36
 title: "Creating impressive proposals in Open Source Programs"
}

Notice: Like and Share if you find this article helpful and resourceful.