1

How to sort objects with lodash by filtered values?

// this is coming from select
var filtered_values = [99, "female"];

// this is my data
var data = [
    { name: "John Doe", age: 24, gender: "male"   },
    { name: "Jona Yap", age: 27, gender: "female" },  // matching: female
    { name: "Einstein", age: 99, gender: "male"   }   // matching: 99
];

// How to sort on this by the values
data = _.sortby(data, filtered_values);

I'd like to sort the list so that, since the filtered values are 99 and female, all objects having values of 99 and|or female should be on the top.

mik01aj
  • 11,928
  • 15
  • 76
  • 119
MeetMahPuppy
  • 305
  • 1
  • 3
  • 13

1 Answers1

4

If you need just to find what matches all criteria, you can use _.filter:

_.filter(data, {gender: 'male', age: 99})

But your requirements seem more complex. Let's write a function to assign scores to the objects and sort them by score:

// I use the fact that when you add booleans they get converted to numbers.
function score(x) { return (x.gender === 'female') + (x.age === 99); }

Or if you don't know which fields to match, you could do:

function score(x) { return _.includes(x, 'female') + _.includes(x, 99); }

Or in a generic way:

var query = [99, "female"];
function score(x) { 
    return _.sum(query, function(y) { return _.includes(x, y); };
}

And then you can use _.orderBy to sort the list by score:

_.orderBy(data, score, 'desc')

Result:

mik01aj
  • 11,928
  • 15
  • 76
  • 119