0

While I have seen this question answered in several other posts, my case seems to be slightly different due to the data that I am receiving from Twitter.

Below is the logic I am using in order to sort the JavaScript Array object, however the problem seems to be that the logic isn't actually sorting the data due to the type of format the date is.

Sample format of the raw date from twitter: Mon Jan 18 17:24:46 +0000 2016

   var UserArraySorted = UserArray.sort(function(a,b){
                return new Date(a.createddate.substring(0,20)) - new Date(b.createddate.substring(0,20));
          });
for(i=0;i < UserArraySorted.length;i++){//Perform some logic here}

Is there anyway to sort my array based on the createddate field I have specified in my code?

2
  • 1
    try new Date(Date.parse(a.createddate)) Commented Jan 18, 2016 at 19:56
  • Take a look at this question: stackoverflow.com/questions/7555025/… Commented Jan 18, 2016 at 19:59

1 Answer 1

1

You almost had it.

Here's the code:

var UserArray = [{
    name: 'Diane',
    createddate: '8/13/2014, 3:45:56 PM'
}, {
    name: 'Jane',
    createddate: '5/15/2015, 4:19:03 PM'
}, {
    name: 'Mary',
    createddate: '7/7/2013, 1:45:00 PM'
}];

UserArray.sort(function(a, b) {
    return new Date(a.createddate) - new Date(b.createddate);
});

for (var i = 0; i < UserArray.length; i++) {
    console.log(UserArray[i]);
}

Output:

Object {name: "Mary", createddate: "7/7/2013, 1:45:00 PM"}
Object {name: "Diane", createddate: "8/13/2014, 3:45:56 PM"}
Object {name: "Jane", createddate: "5/15/2015, 4:19:03 PM"}

Note: Using the sort function of an array will sort the actual array. You assigned the result array to a new variable name UserArraySorted implies that the original UserArray isn't changed (not sure if that's what you intended).

If you don't want to change the original array order, you have to use a map and sort it.

Anyway, converting the strings to date type should do the trick when sorting by dates.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.