简体   繁体   中英

How to sort the object based on array - javascript?

I have months values like below

var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];

 var objects = {
        April:0,
        August:4182,
        December:0,
        February:0,
        January:1,
        July:2,
        June:0,
        March:0,
        May:0,
        November:0,
        October:0,
        September:1518
    }

How to sort the objects based on the months array?

Try with:

var output = [];

for (var k in months) {
  var month = months[k];
  output.push({name: month, value: objects[month]});
}

It will returns you ordered list of objects that contain name and value keys which have proper month name and its value.

var values = [];

for(var i = 0; i < months.length; i++) {
    vals.push(objects[months[i]]);
}

This way you get the object properties' values ordered by the months array.

You can't sort the properties in an object, because the order of the properties is not maintained. If create an object like that, then loop out the properties, you will see that the properties may not be returned in the same order that you put them in the object, and different browsers will return the properties in differend order.

Make the object an array, so that it can maintain the order of the values, and make the lookup array an object so that you can efficiently map a string to a numeric value:

var months = {
  January: 1,
  February: 2,
  March: 3,
  April: 4,
  May: 5,
  June: 6,
  July: 7,
  August: 8,
  September: 9,
  October: 10,
  November: 11,
  December: 12
};

var objects = [
  { name: 'April', value: 0 },
  { name: 'August', value: 4182 },
  { name: 'December', value: 0 },
  { name: 'February', value: 0 },
  { name: 'January', value: 1 },
  { name: 'July', value: 2 },
  { name: 'June', value: 0 },
  { name: 'March', value: 0 },
  { name: 'May', value: 0 },
  { name: 'November', value: 0 },
  { name: 'October', value: 0 },
  { name: 'September', value: 1518 }
];

Now you can sort the array using the object:

objects.sort(function(x,y) { return months[x.name] - months[y.name]; });

Demo: http://jsfiddle.net/7eKfn/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM