对象数组的自定义排序顺序

时间:2021-08-02 19:43:00

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:

我知道我们可以定义json对象数组的自定义排序函数。但是,如果订单既不是desc也不是asc。例如,假设我的数组看起来像:

[ {
    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:

所有以n开头的名称首先排序,然后排序。我尝试了以下自定义排序功能:

_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 个解决方案

#1


13  

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

如果您有任意排序顺序,一个选项是将订单分配给数组,然后使用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].

如果在任一数组中有许多值,则首先创建值索引映射然后使用sortOrder [a.name]可能是值得的。

#1


13  

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

如果您有任意排序顺序,一个选项是将订单分配给数组,然后使用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].

如果在任一数组中有许多值,则首先创建值索引映射然后使用sortOrder [a.name]可能是值得的。