How to sort in specific order - array prototype(not by value or by name)

后端 未结 3 1475
你的背包
你的背包 2020-12-21 06:35

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

book, car and wheel.

I can receive these strings in any order. There may be one or more string

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-21 07:05

    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);

提交回复
热议问题