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

后端 未结 3 1476
你的背包
你的背包 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 06:44

    Your code looks mostly right. I fixed the formatting, etc. and reversed the signs in the sort function.

    Of course, this only handles sorting items with those three exact names. If you need to handle other inputs, you'll have to decide what should happen to those.

    var myitems = [
      {
        name: "book",
      },
      {
        name: "wheel",
      },
      {
        name: "car",
      },
    ];
    
    
    console.log(
      myitems.sort((a, b) => {
        if (a.name === "wheel") {
          return -1;
        }
        if (a.name === "book" && b.name === "car") {
          return -1;
        }
        return 1;
      })
    );

    0 讨论(0)
  • 2020-12-21 06:53

    Since you expect instances (in myitem) of these three strings only, you can use filter on the ordered array, and test the presence of these input strings with Set#has:

    var result = ['wheel', 'book', 'car'].filter(function (s) { 
        return this.has(s) 
    }, new Set(myitem));
    

    // Sample data being received
    var myitem = ['car', 'wheel'];
    
    var result = ['wheel', 'book', 'car'].filter(function (s) { 
        return this.has(s) 
    }, new Set(myitem));
    
    // ordered result
    console.log(result);

    0 讨论(0)
  • 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);

    0 讨论(0)
提交回复
热议问题