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
2

3 Answers 3

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;
Sign up to request clarification or add additional context in comments.

Comments

1

Use angularjs orderByFilter

function MyCtrl($scope, orderByFilter) {
$scope.customer = orderByFilter($scope. customers, 'CreatedOn')[0];
$scope.customer.CurrentCustomer=true
}

Comments

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}
]);

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.