javascript - 根据另一个数组的值对数组进行排序

标签 javascript arrays sorting

如何对这个数组进行排序:

var list = [
    'forms/buttons',
    'forms/fields',
    'layout/common',
    'layout/sidebar',
    'media/captions',
    'media/galleries',
    'typography/headings',
];

基于这个顺序(斜线前的部分):

var needed_order = [
    'typography',
    'forms',
    'media',
    'layout',
];

预期结果:

// [
//     'typography/headings',
//     'forms/buttons',
//     'forms/fields',
//     'media/captions',
//     'media/galleries',
//     'layout/common',
//     'layout/sidebar',
// ]

最佳答案

这应该有帮助

Array.prototype.sortcompareFunction 作为参数来决定排序顺序。 Read more

If compareFunction is supplied, all non-undefined array elements are sorted according to the return value of the compare function (all undefined elements are sorted to the end of the array, with no call to compareFunction)

var list = [
  'forms/buttons',
  'forms/fields',
  'layout/common',
  'layout/sidebar',
  'media/captions',
  'media/galleries',
  'typography/headings',
];

var needed_order = [
  'typography',
  'forms',
  'media',
  'layout',
];

list.sort((a, b) => needed_order.indexOf(a.split('/')[0]) - needed_order.indexOf(b.split('/')[0]));

console.log(list);

关于javascript - 根据另一个数组的值对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51222850/

相关文章:

c++ - 初始化表

php - MySQL表组织进行多维分类

r - 为什么 R 的重复数据在排序数据上表现更好?

java - 按对象属性对对象的 ArrayList 进行排序并组织它们

arrays - 如何减少数组中移动操作的数量?

javascript - 在 Meteor 中使用 list.js 将数据从服务器发布到客户端

javascript - 如何通过 Node JS 从 Python 调用并检索结果?

javascript - 如何使用具有 Angular/ Material 设计的底板?

javascript - 9999.9999 或 9999 或 9999 的正则表达式 :9999

java - 在 ArrayList 中插入不同的数组