New to angularJs and want to get max dated object from list of object.
I have list of customers with property CreatedOn (date)
I want to get single customer and set a property
customer.CurrentCustomer = true; //// when customer having max date
New to angularJs and want to get max dated object from list of object.
I have list of customers with property CreatedOn (date)
I want to get single customer and set a property
customer.CurrentCustomer = true; //// when customer having max date
customers.sort(function(a,b) {
return new Date(a.CreatedOn).getTime() - new Date(b.CreatedOn).getTime()
});
This will sort your array in ascending order by the field CreatedOn.
Then you can pick the last item by:
customers[customers.length - 1]
and hence set the CurrentCustomer:
customers[customers.length - 1].CurrentCustomer = true;
Use angularjs orderByFilter
function MyCtrl($scope, orderByFilter) {
$scope.customer = orderByFilter($scope. customers, 'CreatedOn')[0];
$scope.customer.CurrentCustomer=true
}
You can use libraries like Underscore, Ramda or Lodash. An example using Lodash can be found as given below and in the Link
var users = [
{ 'user': 'fred', 'age': 48 },
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 },
{ 'user': 'barney', 'age': 34 }
];
_.sortBy(users, ['user', 'age']);
An example using Ramda:
var diff = function(a, b) { return a.id > b.id; };
R.sort(diff, [
{ id: 4 },
{ id: 2 },
{ id: 7 },
{id: 5}
]);