0

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
Jinna Balu
  • 6,747
  • 38
  • 47
  • may be help you http://stackoverflow.com/questions/18798568/get-max-and-min-of-object-values-from-javascript-array – Hadi J Apr 06 '16 at 06:34
  • Possible duplicate of [What is the difference between '@' and '=' in directive scope in AngularJS?](http://stackoverflow.com/questions/14050195/what-is-the-difference-between-and-in-directive-scope-in-angularjs) – Jinna Balu Dec 02 '16 at 08:06

3 Answers3

1
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;
war1oc
  • 2,705
  • 1
  • 17
  • 20
1

Use angularjs orderByFilter

function MyCtrl($scope, orderByFilter) {
$scope.customer = orderByFilter($scope. customers, 'CreatedOn')[0];
$scope.customer.CurrentCustomer=true
}
jithin
  • 1,412
  • 2
  • 17
  • 27
1

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}
]);
Madhukar
  • 196
  • 1
  • 7