Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
751 views
in Technique[技术] by (71.8m points)

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

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 strings - max three

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

wheel, book, car

assume the property name is name...

I tried something like this:

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

        return -1;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...