TypeScript 101 – the find() method

TypeScript 101 - the find() method

This is the third post of a blog series where each post will touch a popular TypeScript method, function or feature with example. If you’re starting with TypeScript (or JavaScript) you might not be familiar with all of these powerful tools that can shorten your codebase and help you in day to day development

This post we will discuss the .find() function.

find()

When you have an array but only want a single specific item that matches a certain criteria you can use find(). It will return the first element that matches or return undefined when no match is found.

Let’s say an API call like:

const result = await service.retrieveUsers.promise();

Returns a list of users which looks like this:

const users = [
    {
        username: 'mmaas',
        fullName: 'Marcel Maas'
    },
    {
        username: 'jvzoggel',
        fullName: 'Jan van Zoggel'
    },
    {
        username: 'djanssen',
        fullName: 'Dirk Janssen'
    },
    {
        username: 'rgoossens',
        fullName: 'Roger Goossens'
    }
];

If we would like to find a single user like for example “Jan van Zoggel” out of the array we do not need to loop over it using a forEach but use the  .find() method

The solution using the .find() function would look like this:

const foundUser = users.find(user => user.username === 'jvzoggel');
console.log(foundUser);

You can also do some more advanced stuff by adding the (array)index to the callback and using a more complex functon which either returns true or false to indicate a match:

const foundUser = users.find((user, index) => {
    if (user.username === 'jvzoggel') {
        console.log('index: ' + index);
        return true;
    } else {
        return false;
    }
});
console.log(foundUser);

Summary

So how does it work ? Well in this case if the .find() method gets a match the callback function will return true and the current element will get returned.

Make sure to also check our other TypeScript 101 posts.

Hope it helps!