如何按其值排序对象数组

时间:2017-05-17 07:39:14

标签: javascript jquery html arrays sorting

我有数组响应,我想根据响应数组内对象中的断点变量对数组进行排序。我该怎么办?

var responsive = [
    {
        breakpoint: 1200,
        settings: {
            c: 300
        }
    },
    {
        breakpoint: 780,
        settings: {
            c: 180
        }
    },
    {
        breakpoint: 1400,
        settings: {
            c: 0
        }
    }
];

我试过responsive.sort()但仍然无法正常工作?我该怎么办?

2 个答案:

答案 0 :(得分:3)

您需要为sort()方法提供自己的自定义逻辑,以指定要排序的数组子对象的哪个属性。试试这个:

var responsive = [{
  breakpoint: 1200,
  settings: {
    c: 300
  }
},{
  breakpoint: 780,
  settings: {
    c: 180
  }
},{
  breakpoint: 1400,
  settings: {
    c: 0
  }
}];

responsive.sort(function(a, b) {
  return a.breakpoint > b.breakpoint;
});

console.dir(responsive);

请注意,以上是升序排序。如果您需要降序,请将>换成<

答案 1 :(得分:2)

responsive.sort(function(a,b){
    return a.breakpoint < b.breakpoint;
});