Skip to content

Instantly share code, notes, and snippets.

@RAAbbott
Last active December 16, 2020 19:06
Show Gist options
  • Save RAAbbott/e89d65603b2f33c1ef3ca12986ae3da3 to your computer and use it in GitHub Desktop.
Save RAAbbott/e89d65603b2f33c1ef3ca12986ae3da3 to your computer and use it in GitHub Desktop.
Sort array against a substring. Used for sorting collection by a search term to show most relevant searches first
function sortBySubstring (array, term) {
const func = (a,b) => {
const subStringA = a.substr(0,term.length)
const subStringB = b.substr(0,term.length)
return subStringA.localeCompare(term) - subStringB.localeCompare(term) === 0 ? 1 : -1
}
return array.sort(func)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment