Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/436.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在JavaScript中对数组排序,确保一个元素位于顶部?_Javascript_Sorting - Fatal编程技术网

如何在JavaScript中对数组排序,确保一个元素位于顶部?

如何在JavaScript中对数组排序,确保一个元素位于顶部?,javascript,sorting,Javascript,Sorting,我有一个URL数组,我希望当前URL是最顶端的成员,其余的按字母顺序排列。链接数组以字母顺序升序开始 链接数组如下所示 var links = [ 'http://example.com', 'http://example.net', 'http://stackoverflow.com' ]; 但是我当前的URL可能是http://stackoverflow.com/questions。这应该匹配上面的第二个成员 实现这一目标的最佳方式是什么 谢谢在等待回答时,我想到了

我有一个URL数组,我希望当前URL是最顶端的成员,其余的按字母顺序排列。
链接
数组以字母顺序升序开始

链接
数组如下所示

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()


我遗漏了什么吗?

为什么不采用这种简单的方法

  • 从数组中删除当前URL,例如
    array.splice(array.indexOf(URL),1)
  • 按字母顺序对数组排序
  • 使用
    Array.unshift()
  • 更少的检查,只有简单的拼接和取消移位

    更新

    如果您需要匹配当前域

  • 使用自己的比较函数对数组进行排序
  • 如果当前项目A与url匹配,则返回-1使其冒泡
  • 如果项目B匹配,则返回0使其保持不变
  • 如果A或B都不匹配url,或者A和B都不匹配url,只需返回正常比较对它们进行排序

  • 这是未经测试的,但在理论上它应该是有效的。

    @Marcel Korpel虽然它们是按字母顺序开始的,但在这段代码之后似乎仍然是这样。对不起,我应该指出,URL不是确切的URL,只是一个域列表。将编辑。另外,您可以看到我正在访问数组中每个链接的
    href
    属性,因此
    indexOf()
    很遗憾是不够的。谢谢你的回答:)用
    .sort(function(){…})
    方法更新。对不起,我忘了包括一些相关信息。请参阅我的编辑。
    links.sort(); //first sort alphabetically
    links.unshift(thisURL); //then add the current URL to the top