如何按特定顺序排序 - 数组原型(不是按值或按名称) [英] How to sort in specific order - array prototype(not by value or by name)

查看:93
本文介绍了如何按特定顺序排序 - 数组原型(不是按值或按名称)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望按特定顺序对三个字符串的数组进行排序。

I wish to sort an array of three strings in a specific order.

book,car and wheel。

book, car and wheel.

我可以按任何顺序接收这些字符串。
可能有一个或多个字符串 - 最多三个

I can receive these strings in any order. There may be one or more strings - max three

如果收到一个或多个字符串,我想按照以下确切顺序对字符串进行排序。

I would like to sort the strings in the following exact order if one or more strings are received.

轮子,书籍,汽车

假设物业名称是名称......

assume the property name is name...

我尝试过这样的事情:

myitem.sort((a, b) => {
        if(a.name === 'wheel')
          return 1;
        if(a.name === 'book' && b.name === 'car')
          return 1;

        return -1;


推荐答案

您可以使用具有值及其顺序的对象。使用默认值,您可以将未指定的值移动到数组的开头或结尾。

You could use an object with the order of the values and their order. With a default value, you could move not specified values to start or end of the array.

var order = { wheel: 1, book: 2, car: 3, default: 1000 },
    array = ['foo', 'car', 'book', 'wheel'];
    
array.sort(function (a, b) {
    return (order[a] || order.default) - (order[b] || order.default);
});

console.log(array);

这篇关于如何按特定顺序排序 - 数组原型(不是按值或按名称)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆