0

I used to have an array of arrays and used a sort function to get the proper order like:

var sampleArr = [
  [272, 'Some Title', 1, 1],
  [281, 'Some Other Title', 1, 2],
  [287, 'Another Title', 2, 1]
];

sampleArr.sort(sortCourses);

function sortCourses(a, b){
  if (a[3] == b[3]) {
    return (a[2] - b[2]);
  } else {
    return (a[3] - b[3]);
  }
}

That is the desired result, however we have changed to have the id as a property and the value of the property an array like:

var sampleObj = {
  272: ['Some Title', 1, 1],
  281: ['Some Other Title', 1, 2],
  287: ['Some Other Title 2', 2, 1]
};  

This makes our life a lot easier with lookups for that id, however I am not sure how to sort it.

Can anyone shed some light on the best way to accomplish this? Do I need to convert it back to an array with a function and then run the same sort function? If so, how would I convert the sampleObj back to the original format?

Thanks.

fanfavorite
  • 5,128
  • 1
  • 31
  • 58

2 Answers2

3

Currently the iteration over object properties is left to the browsers. Not all the browsers sorts their iterable properties, so it's not safe to assume this behavior as default.

This other question can explain it: Elements order in a "for (… in …)" loop

If you want obtain something like that, you'll have to rely on non-yet-standard Object.keys() method, sort the resulting array and then access properties using it.

Or, in another and more portable way, you'll have to create a function that extracts all the object's properties in array, sort that array and iterate it to extract every object property.

Community
  • 1
  • 1
Ragnarokkr
  • 2,328
  • 2
  • 21
  • 31
1

I would simply convert it back to the original format. This is easy:

var array = Object.keys(sampleObj).map(function(key) {
  return [Number(key)].concat(sampleObj[key])
})

Object.keys() is an ECMAScript 5 function, so this code won't work in IE6-8, but it will in basically every other browser.

molnarg
  • 2,775
  • 1
  • 19
  • 20