1

Say I have an array like this:

var array = [
  {
    title: "something", 
    date: //date object
  },
  {
    title: "another one", 
    date: //date object
  },
  {
    title: "something else", 
    date: //date object
  },
  {
    title: "title here", 
    date: //date object
  },
  {
    title: "final one", 
    date: //date object
  }
];

The array is in no particular order. I want to order by date, so the object with the most recent date value is at the start and the object with the oldest date is at the end of the array. Then I want to truncate the array so I'm left with 3 objects in it (being the 3 with the most recent date).

Is this possible in javascript?

2

1 Answer 1

3

Surely it is:

array.sort(function(a, b){
    return b.date.getTime() - a.date.getTime();
}).slice(0, 3);

We utilize the .getTime method of Date type objects to sort in descending order.

It gives:

[ { title: 'something', date: Sat, 20 Dec 2014 00:00:00 GMT },
  { title: 'something else', date: Wed, 10 Dec 2014 00:00:00 GMT },
  { title: 'final one', date: Thu, 20 Nov 2014 00:00:00 GMT } ]

on input:

var array = [
  {
    title: "something", 
    date: new Date("2014-12-20")
  },
  {
    title: "another one", 
    date: new Date("2014-10-20")
  },
  {
    title: "something else", 
    date: new Date("2014-12-10")
  },
  {
    title: "title here", 
    date: new Date("2014-02-20")
  },
  {
    title: "final one", 
    date: new Date("2014-11-20")
  }
];
Sign up to request clarification or add additional context in comments.

3 Comments

The dates of the input and output don't seem to match? Confusing
@Coop Refer developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… (fall-back section) there is some strange behaviour with dates provided with /s
@Coop I updated the answer with compliant date format input. Hopefully, that will satisfy your need.

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.