2

I have a array of time as,

 var arr= ["17:30:48","19:30:48","18:30:48","19:30:48","17:40:48","19:10:48","17:10:48","19:30:45","17:13:48","19:13:48","17:30:48","19:28:48"];

I want to get the min and max time out of these. tried if else but its becoming to lengthy by it.is there any easy way to do it.

Hmahwish
  • 2,222
  • 8
  • 26
  • 45
  • 3
    [sort](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) it, take the first and last element. – Yoshi Jul 03 '14 at 06:51
  • Have a look at [this question](http://stackoverflow.com/questions/1669190/javascript-min-max-array-values) – ie. Jul 03 '14 at 06:53
  • @ie. The solutions there only work for arrays of numbers. – Barmar Jul 03 '14 at 06:54
  • @Barmar, solution there is quite common - just use the right comparer. – ie. Jul 03 '14 at 06:57
  • @ie. The solution there uses `Math.max`, not a comparer. – Barmar Jul 03 '14 at 06:58
  • @Barmar, see http://stackoverflow.com/a/1669212/154896 and http://stackoverflow.com/a/13440842/154896 – ie. Jul 03 '14 at 07:00

3 Answers3

1

Check out this fiddle: http://jsfiddle.net/99Eue/12/

Use this sort function and grab the first element. That will get you the max.

arr.sort(function (a,b) {
    if(a > b) { return -1; }
    if(a < b) { return 1; }    
    return 0;
});

Console.log(arr[0]);

Hope this helps.

link
  • 2,480
  • 1
  • 16
  • 18
1
var min = function(arr) {
    return arr.reduce(function(a, b) { return a <= b? a : b;});
};

var max = function(arr) {
    return arr.reduce(function(a, b) { return a <= b? b : a;});
};

reduce is faster but probably better to use good old array.sort for readability

petabyte
  • 1,487
  • 4
  • 15
  • 31
0
var arr= ["17:30:48","19:30:48","17:27:48","19:30:48","17:30:48","19:30:48","17:30:48","19:30:48","17:30:48","19:30:48","17:30:48","19:30:48"];

arr.sort(function (a, b) {
  return new Date('1970/01/01 ' + a) - new Date('1970/01/01 ' + b);
});

alert("Min: " + arr[0] + "     Max: " + arr[arr.length-1]);
John C
  • 666
  • 4
  • 8