Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a collection by another array

I have a collection of names:

[
  {last_name: "A", name: "James" }, 
  {last_name: "A", name: "Robert" }, 
  {last_name: "B", name: "Tim"}, 
  {last_name: "B", name: "Bob" },
  {last_name: "C", name: "Ricky Ticky" }
]

Then I have an array with every last_name in it, in a particular order:

["B", "C", "A"]

How can I sort my collection by the order of last_names in my second array?

What I've tried:

The best solution I have so far is to create a new array, then loop through my collection of names, pushing all of the elements that match my sort array's first index ("B"), then second index ("C"), and finally "A". Seems verbose or maybe underscore.js has a better method.

like image 445
Don P Avatar asked Dec 28 '25 04:12

Don P


1 Answers

Use Underscore's sortBy function, that gives you the ability to sort on an arbitrary feature of the array's elements:

var people = [
  {last_name: "A", name: "James" }, 
  {last_name: "A", name: "Robert" }, 
  {last_name: "B", name: "Tim"}, 
  {last_name: "B", name: "Bob" },
  {last_name: "C", name: "Ricky Ticky" }
];

var lastNameOrder = ["B", "C", "A"];

var sortedPeople = _.sortBy(people, function(person) {
  return lastNameOrder.indexOf(person.last_name);
})

console.log(sortedPeople);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
like image 86
Amadan Avatar answered Dec 30 '25 17:12

Amadan