Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have an array of URLs, and I want the current URL to be the top most member, and the rest in alphabetical order. The links array starts off in alphabetical order ascending.

The links array looks like this...

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

But my current URL may be http://stackoverflow.com/questions. This should match the 2nd member above.

What is the best way to achieve this?

Thanks

like image 253
alex Avatar asked Dec 28 '22 04:12

alex


1 Answers

Why not this simple approach?

  1. Remove the current URL from the array e.g. Array.splice(Array.indexOf(url), 1)
  2. Sort the array alphabetically
  3. Use Array.unshift() to prepend the current URL

Less checks, only a simple splice and unshift.

Update

If you need to match the current domain.

  1. Sort the array using your own compare function
  2. In case the current item A matches the url, return -1 to make it bubble up
  3. In case item B matches, return 0 to make it stay
  4. In case neither A or B, or both A and B match the url, just return the normal comparision to sort them

This is untested, but in theory it should work.

like image 79
Ivo Wetzel Avatar answered May 21 '23 08:05

Ivo Wetzel