hussain hussain - 3 months ago 22
AngularJS Question

How can i get recent or closest date from an array object?

How can i get most recent or closest date from array of object , i tried to implement sortFunction but no luck, Any idea how can i acheive this task ?

ctrl.js

$scope.data = [{
fileDate: Wed Aug 10 2016 10: 10: 44 GMT - 0400(Eastern Daylight Time),
filename: 'server.log'
}, {
fileDate: Tue Aug 30 2016 10: 48: 16 GMT - 0400(Eastern Daylight Time),
filename: 'server1.log'
}, {
fileDate: Wed Aug 31 2016 12: 14: 46 GMT - 0400(Eastern Daylight Time),
filename: 'server3.log'
}]

function sortFunction(a, b) {
var dateA = new Date(a.date).getTime();
var dateB = new Date(b.date).getTime();
return dateA > dateB ? 1 : -1;
};
$scope.data.sort(sortFunction);
console.log('DATE ARRAY', $scope.data);


main.html

<tr ng-repeat="file in data | orderBy:sortType:sortReverse">
<td>{{file.filename}}<label ng-show="showText">currently recording</label></td>
<td>{{file.fileDate |date : "dd.MM.y"}}</td>
<td><button type="button" class="btn btn-primary" ng-click="downloadServerFile(file.filename)">download</button></td>
</tr>

Answer

Your JavaScript object is malformed: quotes are missing around the date strings.

Secondly, they represent strings that JavaScript cannot interpret as Dates.

Here is code to fix those strings before converting them to dates. Then reduce can be use to find the most recent date:

$scope.data = [{
    fileDate: 'Wed Aug 10 2016 10: 10: 44 GMT - 0400(Eastern Daylight Time)',
    filename: 'server.log'
}, {
    fileDate: 'Wed Aug 31 2016 12: 14: 46 GMT - 0400(Eastern Daylight Time)',
    filename: 'server3.log'
}, {
    fileDate: 'Tue Aug 30 2016 10: 48: 16 GMT - 0400(Eastern Daylight Time)',
    filename: 'server1.log'
}];

function dateFromString(str) {
    // Fix date string before conversion -- some spaces need to be removed:
    str = str.fileDate.replace(/([:-])\s+/g,'$1');
    return new Date(str);
}

function mostRecent(a, b) {
    return dateFromString(a) > dateFromString(b) ? a : b;
};

With the above functions you can pick the most recent object by doing:

var lastFile = $scope.data.reduce(mostRecent);

This answers your question. In comments you mentioned: "I just want to get most recent date value and make ng-show boolean value true".

For that you could add a new boolean property to each item, indicating whether it is the last one:

$scope.data.forEach(function (file) {
    file.mostRecent = file === lastFile;
});

You can then use that property in your ng-show attribute.