sorting - How do I sort an array in JavaScript, ensuring one element goes to the top? -


i have array of urls, , want current url top member, , rest in alphabetical order. links array starts off in alphabetical order ascending.

the links array looks this...

var links = [     'http://example.com',     'http://example.net',     'http://stackoverflow.com' ]; 

but current url may http://stackoverflow.com/questions. should match 2nd member above.

what best way achieve this?

thanks

why not simple approach?

  1. remove current url array e.g. array.splice(array.indexof(url), 1)
  2. sort array alphabetically
  3. use array.unshift() prepend current url

less checks, simple splice , unshift.

update

if need match current domain.

  1. sort array using own compare function
  2. in case current item matches url, return -1 make bubble up
  3. in case item b matches, return 0 make stay
  4. in case neither or b, or both , b match url, return normal comparision sort them

this untested, in theory should work.


Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

400 Bad Request on Apache/PHP AddHandler wrapper -

php - Change action and image src url's with jQuery -