将元素排序到数组的顶部

Sorting element to the top of an array

本文关键字:顶部 数组 元素 排序      更新时间:2024-06-19

我正在尝试将自定义排序比较器应用于gullow流(因此我无法自定义数组)。我正在尝试按字母顺序对所有内容进行排序,除了一个共享文件,它应该排序到最前面。

不过,在运行一个简单的jsbin测试时,我看到了同样的问题——我需要的顶部文件排序不正确。

var files = [
  'app/modules/t.css',
  'app/shared/dialogs/c.css',
  'app/shared/directives/m.css',
  'app/shared/scss/app.css',
  'app/shared/modals/a.css',
  'app/shared/modals/b.css'
];
files.sort(function(file1, file2) {
  var sort = 0;
  if (file1.indexOf('shared/scss') > -1) {
     sort = -1;
  } else {
     sort = file1.localeCompare(file2);
  }
  return sort;
});

结果输出不正确,app/shared/scss/app.css只向上移动了两次。

"app/modules/t.css"
"app/shared/dialogs/c.css"
"app/shared/directives/m.css"
"app/shared/scss/app.css"
"app/shared/modals/a.css"
"app/shared/modals/b.css"

以下是我所期待的:

"app/shared/scss/app.css"
"app/modules/t.css"
"app/shared/dialogs/c.css"
"app/shared/directives/m.css"
"app/shared/modals/a.css"
"app/shared/modals/b.css"

嗯,file1不是唯一可以包含app/shared/scss/app.css的变量,还有file2。在排序函数中,您只检查file1

因此,这个排序函数应该按照您想要的方式运行:

files.sort((file1, file2) => {
    let sort = 0, substring = "shared/scss";
    if (file1.includes(substring)) {
        sort = -1;
    }
    else if (file2.includes(substring)) {
        sort = 1;
    }
    else {
        sort = file1.localeCompare(file2);
    }
    return sort;
});

您正在检查file1是否包含shared/scss,但没有检查file2是否包含。添加另一个条件file2.indexOf('shared/scss') > -1,如果为true,则将sort设置为1,使file2显示在顶部。

var files = [
  'app/modules/t.css',
  'app/shared/dialogs/c.css',
  'app/shared/directives/m.css',
  'app/shared/scss/app.css',
  'app/shared/modals/a.css',
  'app/shared/modals/b.css'
];
files.sort(function(file1, file2) {
  var sort = 0;
  if (file1.indexOf('shared/scss') > -1) {
     sort = -1;
  } else if (file2.indexOf('shared/scss') > -1) {
     sort = 1;
  } else {
     sort = file1.localeCompare(file2);
  }
  return sort;
});

这是一个将'shared/scss'提升到首位的提案。

var files = ['app/modules/t.css', 'app/shared/dialogs/c.css', 'app/shared/directives/m.css', 'app/shared/scss/app.css', 'app/shared/modals/a.css', 'app/shared/modals/b.css'];
files.sort(function (a, b) {
    var aa = +!a.match(/shared'/scss/),
        bb = +!b.match(/shared'/scss/);
    return aa - bb || a.localeCompare(b);
});
document.write('<pre> ' + JSON.stringify(files, 0, 4) + '</pre>');