Use includes() in a filter()

Asked

Viewed 36 times

1

The function below is rendering all user names, I need to include in it a way to filter the rendered users according to what is typed in an input text, I tried to use includes() but I’m not getting, as I could apply it in this function???

function renderFoundUsers() {
  let foundUsersHTML = `<div>`;

  foundUsers.filter((user) => {
    const { name } = user;

    const userHTML = `
    <div>
    <ul>
    <li>${name}</li>
    </ul>
    </div>
    `;
    foundUsersHTML += userHTML;
  });
  foundUsersHTML += `</div>`;

  tabfoundUsers.innerHTML = foundUsersHTML;
}

1 answer

0


The method .filter returns a new array, filtered. For this to work you have to return a Boolean value (true or false) inside the callback of this filter to indicate to .filter whether or not to include that entry that is being iterated. For this you could pass an argument to the function with the text to look for, and inside the filter or not function, as this filtering text is empty or not.

I suggest you do it like this:

function renderFoundUsers(searchString) {
  const filteresUsers = searchString ? foundUsers.filter(({
    name
  }) => name.includes(searchString)) : foundUsers;

  const usersHTML = filteresUsers.map(({
    name
  }) => {
    return `
    <div>
      <ul>
        <li>${name}</li>
      </ul>
    </div>
    `;
  }).join('');

  tabfoundUsers.innerHTML = `<div>${usersHTML}</div>`;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.