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?

1 Answer

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'));

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.