Trying to understand find() with arrays

findSexyArtist([
{name: ‘Danny’, isSexy: false },
{name: ‘Brad’, isSexy: true },
{name: ‘Barbara’, isSexy: false}
]) === ‘Brad’;

findSexyArtist([
{name: ‘Kristen’, isSexy: false },
{name: ‘Blake’, isSexy: false },
{name: ‘Angelina’, isSexy: true }
]) === ‘Angelina’;

// to find the name that is true

function findSexyArtist(artists) {

}

//We have a list of artists, and we want to see the name of the sexy one

Please can you tell what I would need to do and why it was done that way, for me to understand to result I need to know the thought process

function findSexyArtist(artists) {
  return artists.find(function (artist) {
    return artist.isSexy;
  });
}

find receives a callback as an argument that is called for every item in the array until a true is returned. When the callback returns true, find know that you found what you want, so it returns the artist object. If true is never returned, then find will return undefined.

A more concise way to write the same thing:

function findSexyArtist(artists) {
  return artists.find(artist => artist.isSexy);
}

Also, I’m not sure if you really want only the name of the artist to be returned or the object itself. The solutions above will return the object itself, if you want the name, then it should be simple:

function findSexyArtist(artists) {
  const artist = artists.find(artist => artist.isSexy);

  return artist ? artist.name : '';
}
1 Like