custom sort order on array of objects

2020-03-01 20:41发布

问题:

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:

[ {
    name: 'u'
  },
  {
    name: 'n'
  },
  {
    name: 'a'
  },
  { 
    name: 'n',
  } 
]

Output should look like:

[ {
    name: 'n'
  },
  {
    name: 'n'
  },
  {
    name: 'a'
  },
  { 
    name: 'u',
  } 
]

Where all the names starting with n are sorted first and then the rest. I have tried the following custom sort function:

_sortByName(a, b){
        if (a.name === 'n'){
            return 1;
        } else if(b.name === 'n'){
            return 1;
        } else if(a.name < b.name){
            return 1;
        } else if(a.name > b.name){
            return -1;
        }
    }

But the order returned for objects is wrong. What is going wrong here?

回答1:

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].