简体   繁体   中英

Sort an array based on another array's values

How can I sort this array:

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

based on this order(the part before slash):

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

The expected result:

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

This should help

Array.prototype.sort takes a compareFunction as an argument to decide the sort order. 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); 

You could sort by the first appearance in the ˋneeded_orderˋ array:

const getPriority = el => needed_order.findIndex(order => el.includes(order));

list.sort((a, b) => getPriority(a) - getPriority(b));

You could sort by the infex of the string which starts with the items to sort.

 var list = ['forms/buttons', 'forms/fields', 'layout/common', 'layout/sidebar', 'media/captions', 'media/galleries', 'typography/headings'], order = ['typography', 'forms', 'media', 'layout']; list.sort((a, b) => order.findIndex(v => a.startsWith(v)) - order.findIndex(v => b.startsWith(v))); console.log(list); 

A faster version for huge data, could be to store the key index values in a hash table and use it for sorting.

 function getS(s) { return s.match(/^[^\\/]*/)[0]; } var list = ['forms/buttons', 'forms/fields', 'layout/common', 'layout/sidebar', 'media/captions', 'media/galleries', 'typography/headings'], order = ['typography', 'forms', 'media', 'layout'], hash = Object.assign(...order.map((k, v) => ({ [k]: v }))); list.sort((a, b) => hash[getS(a)] - hash[getS(b)]); console.log(list); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM