admin管理员组

文章数量:1134589

Given the following array of objects, I need to ascending sort them by the date field.

var myArray = [
  {
    name: "Joe Blow",
    date: "Mon Oct 31 2016 00:00:00 GMT-0700 (PDT)"
  },
  {
    name: "Sam Snead",
    date: "Sun Oct 30 2016 00:00:00 GMT-0700 (PDT)"
  },
  {
    name: "John Smith",
    date: "Sat Oct 29 2016 00:00:00 GMT-0700 (PDT)"  
  }
];

In the above example, the final result would be John Smith, Sam Snead, and Joe Blow.

I am trying to use lodash's _.sortBy(), but I can't get any sorting to take place no matter how I try to use it:

_.sortBy(myArray, function(dateObj) {
  return dateObj.date;
});

or

_.sortBy(myArray, 'date');

What do I need to change to get my array sorted properly? I also have Moment.js, so I can use it to format the date string if needed. I tried converting the date property using .unix(), but that didn't make a difference.

Thanks.

Given the following array of objects, I need to ascending sort them by the date field.

var myArray = [
  {
    name: "Joe Blow",
    date: "Mon Oct 31 2016 00:00:00 GMT-0700 (PDT)"
  },
  {
    name: "Sam Snead",
    date: "Sun Oct 30 2016 00:00:00 GMT-0700 (PDT)"
  },
  {
    name: "John Smith",
    date: "Sat Oct 29 2016 00:00:00 GMT-0700 (PDT)"  
  }
];

In the above example, the final result would be John Smith, Sam Snead, and Joe Blow.

I am trying to use lodash's _.sortBy(), but I can't get any sorting to take place no matter how I try to use it:

_.sortBy(myArray, function(dateObj) {
  return dateObj.date;
});

or

_.sortBy(myArray, 'date');

What do I need to change to get my array sorted properly? I also have Moment.js, so I can use it to format the date string if needed. I tried converting the date property using .unix(), but that didn't make a difference.

Thanks.

Share Improve this question edited Oct 10, 2022 at 15:38 Dave Mackey 4,42221 gold badges82 silver badges144 bronze badges asked Dec 5, 2016 at 1:12 wonder95wonder95 4,2258 gold badges48 silver badges82 bronze badges 6
  • Are those date objects, or date strings? – Andreas Louv Commented Dec 5, 2016 at 1:15
  • Standard Javascript date strings. As I said, I can convert them to another format with Moment first if needed, but converting to unix didn't seem to work, and that seems to be the easiest format for sorting. – wonder95 Commented Dec 5, 2016 at 1:17
  • Are the values dates or strings? – Dekel Commented Dec 5, 2016 at 1:20
  • _.sortBy doesn't seem to sort in place (unlike Array#sort method) – Jaromanda X Commented Dec 5, 2016 at 1:20
  • 3 _.sortBy(myArray, ['date']) should work. For '2018-08-28T17:38:00' date format it works. – Chaki_Black Commented Aug 17, 2018 at 14:42
 |  Show 1 more comment

8 Answers 8

Reset to default 111

You don't really need lodash. You can use JavaScript's Array.prototype.sort method.

You'll need to create Date objects from your date strings before you can compare them.

var myArray = [{
  name: "Joe Blow",
  date: "Mon Oct 31 2016 00:00:00 GMT-0700 (PDT)"
}, {
  name: "Sam Snead",
  date: "Sun Oct 30 2016 00:00:00 GMT-0700 (PDT)"
}, {
  name: "John Smith",
  date: "Sat Oct 29 2016 00:00:00 GMT-0700 (PDT)"
}];

myArray.sort(function compare(a, b) {
  var dateA = new Date(a.date);
  var dateB = new Date(b.date);
  return dateA - dateB;
});

console.log(myArray);

Here's a solution using standard Javascript by converting both values to date object and comparing their value.

myArray.sort((d1, d2) => new Date(d1.date).getTime() - new Date(d2.date).getTime());

A complete snippet:

var myArray = [
  {
    name: "Joe Blow",
    date: "Mon Oct 31 2016 00:00:00 GMT-0700 (PDT)"
  },
  {
    name: "Sam Snead",
    date: "Sun Oct 30 2016 00:00:00 GMT-0700 (PDT)"
  },
  {
    name: "John Smith",
    date: "Sat Oct 29 2016 00:00:00 GMT-0700 (PDT)"  
  }
];

myArray.sort((d1, d2) => new Date(d1.date).getTime() - new Date(d2.date).getTime());

console.log(myArray);

Your date values are strings, so you need to use the new Date() constructor to change them to javascript date objects. This way you can sort them (using _.sortBy).

var myArray = [
  {
    name: "Joe Blow",
    date: "Mon Oct 31 2016 00:00:00 GMT-0700 (PDT)"
  },
  {
    name: "Sam Snead",
    date: "Sun Oct 30 2016 00:00:00 GMT-0700 (PDT)"
  },
  {
    name: "John Smith",
    date: "Sat Oct 29 2016 00:00:00 GMT-0700 (PDT)"  
  }
];

myArray = _.sortBy(myArray, function(dateObj) {
  return new Date(dateObj.date);
});

console.log(myArray)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

If you are trying to use lodash to sort dates in ascending or descending order for your array of objects, you should use _.orderBy instead of _.sortBy

https://lodash.com/docs/4.17.15#orderBy, this method allows specifying sort orders either by 'asc' or 'desc'

An example would be:

const sortedArray = _(myArray.orderBy([
      function(object) {
        return new Date(object.date);
      }],["desc"])

A cleaner way using Lodash orderBy:

import _ from 'lodash'

const sortedArray = _.orderBy(myArray, [(obj) => new Date(obj.date)], ['asc'])

just write _.sortBy({yourCollection}, {the field name});

lodash will automatically figure that this is a date and it'll work like a magic!

Awesome!

Inspired by others answers and noticing that you used moment.js and lodash, you can combine both with _.orderBy lodash method:

import moment from 'moment'
import * as _ from 'lodash'

let myArray = [
  {
    name: "Joe Blow",
    date: "Mon Oct 31 2016 00:00:00 GMT-0700 (PDT)"
  },
  {
    name: "Sam Snead",
    date: "Sun Oct 30 2016 00:00:00 GMT-0700 (PDT)"
  },
  {
    name: "John Smith",
    date: "Sat Oct 29 2016 00:00:00 GMT-0700 (PDT)"  
  }
];


myArray = _.orderBy(myArray, [(item) => {
            return moment(item.date).format('YYYY-MM-DD')
         }], ['desc'])

this has worked for me

myArray = _.orderBy(myArray, [item => item.lastModified], ['desc']);

本文标签: javascriptSort array of objects with date field by dateStack Overflow