Could I use "_.filter" with "sort (ase, dsc)" of object array in underscore/lodash?


#1

I would like to _.filter() with sort(asc, dsc) in undersore/lodash

var users = [
  {id: '001', 'user': 'barney', 'age': 56, 'active': true },
  {id: '002', 'user': 'fred',   'age': 40, 'active': false },
  {id: '003', 'user': 'alled',   'age': 50, 'active': false }
];


var result = _.filter(users, function(chr) {
  return chr.age <= 50; // sort by user property
})


#2

I think you’re looking for this, don’t need underscore

var youngPeople = users.filter(function (user) {
  return (user.age <= 50);
});

#3

Thanks for your reply, but I would to use sort/order by.


#4

Look at chain. It simly iterate your array with a few underscore methods at the time


#5
var youngPeopleSorted = _.sortBy(youngPeople, function (user) {
  return user.age;
});

#6

Could I use asc or desc style?


#7

default is ascending, but if you want descending just write return -user.age;

This is not really a Meteor question btw, are you not using a collection for this? Mongo has nice query syntax for doing these things.


#8

Thanks all, look great :smiley: