custom sort order on array of objects

前端 未结 1 427
灰色年华
灰色年华 2021-01-04 22:21

I know we can define our custom sort function of array of json objects. But what if the order is neither desc nor asc. For example lets say my array looks like:

相关标签:
1条回答
  • 2021-01-04 23:02

    If you have an arbitrary sort order, one option is to assign the order to an array and then use indexOf:

    var sortOrder = ['n', 'a', 'u'];
    var myArray = [{
        name: 'u'
      },
      {
        name: 'n'
      },
      {
        name: 'a'
      },
      {
        name: 'n'
      }
    ];
    myArray.sort(function(a, b) {
      return sortOrder.indexOf(a.name) - sortOrder.indexOf(b.name);
    });
    
    console.log(myArray);

    If you have many values in either array, it might be worthwhile creating a value-index map first and then using sortOrder[a.name].

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