-3
var countries = ["Algeria", "Canada", "Danmark", "Estonia"];
var search = "da";

Now I wish to sort this list so I get the following:

sortedCountries === ["Danmark", "Canada", "Algeria", "Estonia"]

I want DAnmark to come before CanaDA, because "da" is found earlier in that string. I do NOT wish to do a sort in ascending/descending order.

1
  • Comments are not for extended discussion; this conversation has been moved to chat. Commented Aug 19, 2019 at 9:45

1 Answer 1

0

You can use Array.prototype.sort:

var countries = ["Algeria", "Canada", "Danmark", "Estonia"];
var search = "da";

console.log(countries.sort((a, b) => {
  a = a.toLowerCase().indexOf(search) + 1
  b = b.toLowerCase().indexOf(search) + 1
  
  if(!a && !b) return 0
  else if(!a) return 1
  else if(!b) return -1
  else return a - b
}))

We could write this as a utility function too:

var countries = ["Algeria", "Canada", "Danmark", "Estonia"]

const searchCountries = (a, s) => a.sort((a, b) => {
  s = s.toLowerCase()
  a = a.toLowerCase().indexOf(s) + 1
  b = b.toLowerCase().indexOf(s) + 1
  
  if(!a && !b) return 0 // don't sort if search fails for both
  else if(!a) return 1 // swap results since b has a value, but a doesn't
  else if(!b) return -1 // leave results since a has a value, but b doesn't
  else return a - b // otherwise, sort by indexOf result
})

console.log(searchCountries(countries, 'da'))
console.log(searchCountries(countries, 'a'))
console.log(searchCountries(countries, prompt()))

Sign up to request clarification or add additional context in comments.

11 Comments

if(!a && !b) return 0 looks redundant.
@zerkms It looks it, but it isn't, since I have to make all the other checks AFTER making that one, otherwise the ordering goes odd, and it allows for an early return :)
At least with their input array it would return the same result :shrug:
@zerkms True :P
Not sure to be honest :P @SimonSondrupKristensen
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.