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 badges3 Answers
Reset to default 8Why not this simple approach?
- Remove the current URL from the array e.g.
Array.splice(Array.indexOf(url), 1)
- Sort the array alphabetically
- 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.
- Sort the array using your own pare function
- In case the current item A matches the url, return -1 to make it bubble up
- In case item B matches, return 0 to make it stay
- 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
版权声明:本文标题:sorting - How do I sort an array in JavaScript, ensuring one element goes to the top? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741220984a2360965.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论