对象数组的自定义排序顺序 [英] custom sort order on array of objects

查看:189
本文介绍了对象数组的自定义排序顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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',
  } 
]

输出应如下所示:

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

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

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?

推荐答案

如果您有任意排序顺序,一个选项是将订单分配给数组并且然后使用 indexOf

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

如果在任一阵列中有多个值,那么创建一个值可能是值得的 - 首先使用索引映射,然后使用 sortOrder [a.name]

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

这篇关于对象数组的自定义排序顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆