如何对这个数组进行排序:
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.sort
将 compareFunction
作为参数来决定排序顺序。 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 tocompareFunction
)
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/