Reputation: 5939
I have an array which contains many objects. I am trying to sort the array based on the key value of each object.
So, the object looks like this:
var info = [
{name: 'Adam', age: '1987-01-09T18:23:20.000Z'},
{name: 'Issac', age: '1988-09-02T11:17:11.000Z'},
{name: 'Tom', age: '2003-08-07T13:07:03.000Z'},
{name: 'Jane', age: '1997-17-01T14:57:41.000Z'}
];
I am trying saved the new (sorted) data into a variable called sorted
;
var sorted = info.forEach(function(person) {
var age = moment(String(person.age)).format('MM/DD/YYYY');
return age
}, this);
console.log(sorted)
So, I have momentjs, to change the date into a time format that can easily be
sorted, but the sorted
console.log shows me undefined
.
Honestly, I don't even know how sorting functions work. At least it should return the age
from the loop and thus console.log()
should not have been empty
Upvotes: 0
Views: 79
Reputation: 1885
Try for this:
var arrayOfObject = [
{name: 'Adam', age: '1987-01-09T18:23:20.000Z'},
{name: 'Issac', age: '1988-09-02T11:17:11.000Z'},
{name: 'Tom', age: '2003-08-07T13:07:03.000Z'},
{name: 'Jane', age: '1997-12-01T14:57:41.000Z'}
];
arrayOfObject.sort(function (a, b) {
return ((new Date(a.age)).getTime() - (new Date(b.age)).getTime());
})
Upvotes: 0
Reputation: 2012
forEach
isn't used to sort, neither is it used to change an array. For sorting, you should use sort
.
The sort
function sorts an array by comparing elements in pairs. You need to give it a function that will "compare" two elements. The "compare" function takes in two argument a
and b
, and should return a negative number if a<b
, 0
if they are the same, and a positive number if a>b
.
Therefore, the code below could works:
var info = [
{name: 'Adam', age: '1987-01-09T18:23:20.000Z'},
{name: 'Issac', age: '1988-09-02T11:17:11.000Z'},
{name: 'Tom', age: '2003-08-07T13:07:03.000Z'},
{name: 'Jane', age: '1997-12-01T14:57:41.000Z'}
];
info.sort(function (a, b) {
return (new Date(a.age)).getTime() - (new Date(b.age)).getTime()
})
Also notice that the fourth date you have given - 1997-17-01T14:57:41.000Z
, is invalid since month number must be less than 13.
Upvotes: 2