简体   繁体   中英

javascript sorting array of objects by date

I have a function that takes an array of objects and I need to sort the array by day; it looks like this:

function Myfunction (TheDays) {

  var TheDaysToSort = $.extend(false, TheDays);

  function SortOrder (a, b) {
     var Day1 = a['TheDate'];
     var Day2 = b['TheDate'];
     return Day1 - Day2;
  };

  TheDaysToSort.sort(SortOrder);
}

I get an error Uncaught TypeError: Object #<Object> has no method 'sort'

You can use .sort() on arrays. You cannot .sort() an object as objects don't have an order to their properties and thus don't have a .sort() method.

If TheDays is an array, then it's unclear what you're trying to do with the $.extend(false, TheDays); line of code. If you can explain what that is supposed to do, we can probably help with what you should be doing instead so that TheDaysToSort is an array that you sort.

For example, if you're trying to just make a copy of TheDays , then I'd suggest this line instead of the .extend() line:

var TheDaysToSort = TheDays.slice(0);  // make copy of array for sorting

You should use:

 var TheDaysToSort = $.extend([], TheDays);

then TheDaysToSort will be correct array which will be sorted successfully.

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