0

I have array responsive and I want to sort my array based on the breakpoint variable in the object inside the responsive array. How can I do it?

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

I tried responsive.sort() but still not working? How can I do it?

Jemuel Elimanco
  • 416
  • 2
  • 4
  • 20

2 Answers2

3

You need to provide the sort() method with your own custom logic to specify which property of the array's child object to sort by. Try this:

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

Note that the above is an ascending sort. If you need descending, swap > for a <.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
2
responsive.sort(function(a,b){
    return a.breakpoint < b.breakpoint;
});
Master Yoda
  • 531
  • 8
  • 22