Home > Net >  JavaScript filtering a list of users by search term then sorting where users that start with the sea
JavaScript filtering a list of users by search term then sorting where users that start with the sea

Time:07-14

I need to sort a list of users on the client which we get in a format like so:

const users = ["Armand Collins", "Any user", "Marc Hayes", "mark"];

We would filter the list with a search term, so if someone entered "ma" as a term then they would see the following users in the UI:

const users = ["Armand Collins", "Marc Hayes", "mark"];

This is all fine but the sorting requirement dictates that although we have partially matched all 3 users we want to see them in the order where the entries that start with the term are sorted (alphabetically) first and the entries that contain the term come afterwards again in alphabetical order.

So the desired sort order would be for the term "ma":

const users = ["Marc Hayes", "mark", "Armand Collins"];

How do I go about achieving this in JavaScript?

CodePudding user response:

You could sort by looking if the string starts with the wanted string.

const
    find = (array, search) => {
        search = search.toLowerCase();
        return array
            .filter(v => v.toLowerCase().includes(search))
            .sort((a, b) => 
                b.toLowerCase().startsWith(search) - a.toLowerCase().startsWith(search) ||
                a.localeCompare(b)
            );
    },
    users = ["Armand Collins", "Any user", "Marc Hayes", "mark"];

console.log(find(users, 'ma'));

CodePudding user response:

const users = [ 'Armand Collins', 'Any user', 'Marc Hayes', 'mark', 'amark' ]

const search = 'ma'

const result = users
  .filter(v => v.toLowerCase().includes(search))
  .sort((a, b) => {
    let indexA = a.toLowerCase().indexOf(search.toLowerCase())
    let indexB = b.toLowerCase().indexOf(search.toLowerCase())
    if (indexA > -1 && indexB > -1) {
      return indexA - indexB
    } else if (indexA > -1 && indexB === -1) {
      return -1
    } else if (indexA === -1 && indexB > -1) {
      return 1
    } else {
      return 0
    }
  })

console.log(result)

CodePudding user response:

just use filter function and check that string exist in array or not with includes function.

const users = ["Armand Collins", "Any user", "Marc Hayes", "mark"];
    const searchTerm = 'ma';
    const findUsers = users.filter(f => f.toLowerCase().includes(searchTerm.toLowerCase()))
    console.log(findUsers)

  • Related