如何在JavaScript中对数组排序,确保一个元素位于顶部?
我有一个URL数组,我希望当前URL是最顶端的成员,其余的按字母顺序排列。如何在JavaScript中对数组排序,确保一个元素位于顶部?,javascript,sorting,Javascript,Sorting,我有一个URL数组,我希望当前URL是最顶端的成员,其余的按字母顺序排列。链接数组以字母顺序升序开始 链接数组如下所示 var links = [ 'http://example.com', 'http://example.net', 'http://stackoverflow.com' ]; 但是我当前的URL可能是http://stackoverflow.com/questions。这应该匹配上面的第二个成员 实现这一目标的最佳方式是什么 谢谢在等待回答时,我想到了
链接
数组以字母顺序升序开始
链接
数组如下所示
var links = [
'http://example.com',
'http://example.net',
'http://stackoverflow.com'
];
但是我当前的URL可能是http://stackoverflow.com/questions
。这应该匹配上面的第二个成员
实现这一目标的最佳方式是什么
谢谢在等待回答时,我想到了这个
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);
var matchRegex=newregexp('^'+RegExp.escape('http://'+window.location.hostname));
var newLinks=[];
对于(变量i=0,linksLength=links.length;i
似乎工作得很好。为什么不使用.unshift()
我遗漏了什么吗?为什么不采用这种简单的方法
array.splice(array.indexOf(URL),1)
Array.unshift()
这是未经测试的,但在理论上它应该是有效的。@Marcel Korpel虽然它们是按字母顺序开始的,但在这段代码之后似乎仍然是这样。对不起,我应该指出,URL不是确切的URL,只是一个域列表。将编辑。另外,您可以看到我正在访问数组中每个链接的
href
属性,因此indexOf()
很遗憾是不够的。谢谢你的回答:)用.sort(function(){…})
方法更新。对不起,我忘了包括一些相关信息。请参阅我的编辑。
links.sort(); //first sort alphabetically
links.unshift(thisURL); //then add the current URL to the top