‘Expected to return a value at the end of arrow function’ – Is there another way to do this other than filter?

Here is my code –

  {data?.results
              ?.filter(item => {
                if (searchTerm === '') {
                  return item;
                } else if (
                  item.title
                    .toLowerCase()
                    .includes(searchTerm.toLowerCase()) ||
                  item.description
                    .toLowerCase()
                    .includes(searchTerm.toLowerCase())
                ) {
                  return playlist;
                }
              })
              .map((item, index) => (
                <StoreItem
                  key={index}
                  id={item.id}
                  title={item.title}
                  description={item.description}
                />
              ))}

I have implemented a search input which updates the state ‘searchTerm’ onChange. I am then running this searchTerm against an array of objects. This currently works and gives me back real-time results as I’m searching however I am getting two eslint errors:

Expected to return a value at the end of an arrow function – array-callback-return & consistent return

I know it’s because I am not returning anything outside of the if/else statement within filter however I can’t figure out how else I can do this.

Answer

There is a default branch you haven’t provided a return value for.

                if (searchTerm === '') {
                  return item;
                } else if (
                  return item.title
                    .toLowerCase()
                    .includes(searchTerm.toLowerCase()) ||
                  playlist.description
                    .toLowerCase()
                    .includes(searchTerm.toLowerCase())
                ) {
                  return playlist;
                } else {
                  // return something;
                }

Furthermore, item and playlist seem to be objects, which are not useful values for filtering an array since you should return a Boolean value. You might mean…

?.filter(item => {
  if (searchTerm === '') {
    return true;
  } else if (
    item.title
      .toLowerCase()
      .includes(searchTerm.toLowerCase()) ||
    playlist.description
       .toLowerCase()
       .includes(searchTerm.toLowerCase())
  ) {
    return true;
  } else {
    return false;
  }
})

If it’s the case, the function can be simpified to…

?.filter(item => (
  searchTerm === '' ||
  item.title
    .toLowerCase()
    .includes(searchTerm.toLowerCase()) ||
  playlist.description
     .toLowerCase()
     .includes(searchTerm.toLowerCase())
);