-1

Trying to sort an object with some data depending on a number inside of it

For example:

    var object = {
        sort: 15,
        name: "Value 2"
    },
    {
        sort: 10,
        name: "Value 1"
    }

etc.

So I basically want to sort the object here by the 'sort' value inside of it. Is there an easy way to do this?

Thanks!

kraxie
  • 11
  • 2
  • 4

4 Answers4

0

If it's an array then use Array#sort method to sort using a custom compare function.

var object = [{
    sort: 15,
    name: "Value 2"
  },
  {
    sort: 10,
    name: "Value 1"
  }
];

object.sort(function(a, b) {
  return a.sort - b.sort
});

console.log(object);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

considering this example which is a valid js:

var myArray = [{
        sort: 15,
        name: "Value 2"
    },
    {
        sort: 10,
        name: "Value 1"
    }]
myArray.sort(function(item, nextItem){
  return item.sort - nextItem.sort;
});
Fanyo SILIADIN
  • 802
  • 5
  • 11
0

I assume you are talking about an array of objects. i.e:

var object = [{sort: 15,name: "Value 2"},{sort: 10,name: "Value 1"}]

In that case you can use Array.prototype.sort()

var obj = [{
  sort: 15,
  name: "Value 2"
}, {
  sort: 10,
  name: "Value 1"
}]

obj.sort(function(itemA, itemB){
  return itemA.sort - itemB.sort
});

console.log(obj)
Nope
  • 22,147
  • 7
  • 47
  • 72
0

This can be passing a comparison function to the array sort function.

For example:

var someData = [{id:2, name:"Jacob"}, 
                {id:1, name:"Josh"}, 
                {id:3, name:"Trevor"}];

someData.sort(function(a,b) { return a.id - b.id});