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?
- remove current url array e.g.
array.splice(array.indexof(url), 1) - sort array alphabetically
- use
array.unshift()prepend current url
less checks, simple splice , unshift.
update
if need match current domain.
- sort array using own compare function
- in case current item matches url, return -1 make bubble up
- in case item b matches, return 0 make stay
- in case neither or b, or both , b match url, return normal comparision sort them
this untested, in theory should work.
Comments
Post a Comment