6

I've tried using underscorejs, min and max methods but they can't handle strings. From what i've read and learnt anyway, since I get infinite back from both.

My array looks like : dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"]

How can I grab the last and the first date in these?

I tried using sort also that looks like : _.chain(dateData).sort().first().value() but I get back the last item in the array rather then the last date in the array.

6
  • Sort it..Get the first and last item from sorted array.. Commented Jun 23, 2016 at 16:09
  • @Rayon I've tried _.chain(dateData).sort().last().value() but I get back the last item in the array. Not the last date in the array. I may just be being stupid though :) Commented Jun 23, 2016 at 16:10
  • 2
    @SmurfEkko, you need to specify the sorting behavior by writing a custom comparison function. Commented Jun 23, 2016 at 16:11
  • @zzzzBov So the way to do this would be to read each item in my array and work out of the first two digits which is higher, then on to the second, and then third? Is that how i'd do it? Commented Jun 23, 2016 at 16:13
  • @SmurfEkko, no, you'd parse the values as a date, and then compare the date objects. Consider using a lib like momentjs for proper date parsing. Commented Jun 23, 2016 at 16:15

7 Answers 7

12

var dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"];

function dateToNum(d) {
  // Convert date "26/06/2016" to 20160626
  d = d.split("/"); return Number(d[2]+d[1]+d[0]);
}

dateData.sort(function(a,b){
  return dateToNum(a) - dateToNum(b);
});

console.log( dateData );

To retrieve the first, last date:

var firstDate = dateData[0];
var lastDate  = dateData[dateData.length -1];

Basically, if you first convert all your 26/06/2016 to a date Number like 20160626 you can .sort() those numbers instead.

so you're basically sorting:

20140626  
20140604  
20140513  
20140720  

resulting in:

[  
  "13/05/2016",  
  "04/06/2016",  
  "26/06/2016",  
  "20/07/2016"  
]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man, this is exactly what I was looking for. I didn't even think about sorting then before hand. I was trying to just iterate over each item in the array and work it out from there. This is a much better method. Thanks again!
2

If we can format the dateStrings in a particular format, then sorting them as strings also sorts them as dates e.g. YYYY-MM-DD.

You can use localeCompare to compare strings.You can use following code to sort the dates:

dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"]

dateData.sort(function(a, b){
  var A = a.split("/");
  var B = b.split("/");
  var strA = [ A[2], A[1], A[0] ].join("/");
  var strB = [ B[2], B[1], B[0] ].join("/");
  return strA.localeCompare( strB );      
});

console.log( dateData );

Once sorted, you can get the min and max dates as:

var minDate = dateData[0];
var maxDate = dateData[ dateData.length - 1 ];

Comments

1

The getTime() method returns the numeric value corresponding to the time for the specified date according to universal time. Date.getTime()

dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"]
.map(a=>a.split('/').reverse().join('/'))
.sort((a,b)=>new Date(a).getTime() - new Date(b).getTime());
console.log(dateData);

Comments

1

A number people have already touched on this, but you need to convert the date strings to something that can be compared in the sort function. The one thing I haven't seen shared is how to get the first and last dates. This should do the trick:

//original date array
var dateData = ["04/06/2016", "13/05/2016", "20/07/2016","26/06/2016"];

//map through the original array and convert the dates to js date objects
var formattedDates = dateData.map(function(date){
    var splitDate = date.split("/")
    return new Date(splitDate[2],splitDate[1]-1,splitDate[0])
})

//sort the dates
formattedDates.sort(function(a,b){
  // Turn your strings into dates, and then subtract them
  // to get a value that is either negative, positive, or zero.
  return new Date(a) - new Date(b);
});

//Now you can get the first and last dates:
var firstDate = formattedDates[0]
var lastDate = formattedDates[formattedDates.length-1];

//log to check:
console.log('first date: ', firstDate)
console.log('last date: ', lastDate)

Comments

0

One way I know to do this is using the .sort() function for a string. https://msdn.microsoft.com/en-us/library/4b4fbfhk(v=vs.94).aspx

You would have to change your array into YYYY-MM-DD

then you could have the following code

var dateData = ["2016/06/26", "2016/06/04", "2016/05/13", "2016/07/20"]; dateData.sort(); var first = dateData[0]; var last = dateData[dateData.length-1];

where first is the earliest date and last is the latest date

Comments

0

To be easier for the subsequest operations, change the format to be like this: YYYY/MM/DD. This way regular sorting will get you the min and max properly, and you won't need further parsing. Helper function to sort would be like this:

for(var i=0;i<dateData.length;++i)
{
    var split = dateData[i].split("/");
    dateData[i] = split.reverse().join("/");
}

Comments

0

Roko's answer worked for me, and +1. And Jose had a similar thought to me, +1...
...There's an easier and more robust way: .valueOf()

converting date string to number:

const dateAsNumber = new Date(dateAsString).valueOf()

JS has a built in method/function for calculating the number of milliseconds that have passed since a date; that's .valueOf(), which can be called on a Date object. So, turn your date string into a Date object (with "new Date()" with the date string as the argument), and then convert to milliseconds.

After that, the normal .sort() works fine. As shown below, for your convenience:

const arrayOfDateStrings = ["5/01/2012", "10/01/2020", "10/01/2019", "11/30/2016", "10/01/2021", "02/01/2020"];

const sortedArray = arrayOfDateStrings.sort((a,b)=>new Date(a).valueOf() - new Date(b).valueOf());

console.log(sortedArray);

Or Moment.js can be used instead of the built-in Date object/functions, that works in a very similar way.

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.