admin管理员组

文章数量:1279118

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 = [
    '',
    '',
    ''
];

But my current URL may be . This should match the 2nd member above.

What is the best way to achieve this?

Thanks

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.',
    'http://example',
    'http://stackoverflow.'
];

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

What is the best way to achieve this?

Thanks

Share Improve this question edited Dec 3, 2010 at 1:09 alex asked Dec 3, 2010 at 0:51 alexalex 491k204 gold badges889 silver badges991 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

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 pare 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 parision to sort them

This is untested, but in theory it should work.

Whilst waiting for an answer, I came up with this...

var matchRegex = new RegExp('^' + RegExp.escape('http://' + window.location.hostname));

var newLinks = [];

for (var i = 0, linksLength = links.length; i < linksLength; i++) {

      if (links[i].href.match(matchRegex)) {
          newLinks.push(links[i]);
          links.splice(i, 1);
          break;
      };

};

newLinks = newLinks.concat(links);

Seems to work nicely.

Why don't you use .unshift()?

links.sort(); //first sort alphabetically
links.unshift(thisURL); //then add the current URL to the top

Am I missing something?

本文标签: sortingHow do I sort an array in JavaScriptensuring one element goes to the topStack Overflow