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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With