Lodash's "sortBy" method helps you sort data in your collections and "sortedIndex" helps you find where to place new data. In this video, John walks you through how to use each of these methods and how they can work together.
To sort collections using lodash, you can use lodash as a sort by. To sort this array of names that we have here, you just say, _.sortBy, pass in the collection, and then assign that to something, we'll just call it, sorted collection, and then log it out.
You can see, the results are Abe, Beth, Chris, Yolanda and Zack, which is proper alphabetical order. If I want to reverse the order, the easiest way to do that is to just use reverse. Just type, .reverse here, run it again, and you can see now it goes from Zack all the way to Abe.
To sort a more complex structure or collection with objects and properties, you can see this one has age and name, and we can sort on either of those. We use the same syntax of, _.sortBy, pass in the collection, pass in the property name of age, and then we'll use that sorted collection and then just log it out.
You can see in the results, it's now sorted by age, all the way from 8 to 90, but the names aren't sorted. You can see that Abe and Beth are out of order. If I want to change it to name, just type name, hit run again, and you can see now it's sorted by name instead of age. Abe, Beth, and Chris.
Now if we want to add a new guy in here, I will just go ahead and say, "Bar new guy," and create someone with an age of 40, and a name of John. That's a great name. Then I can use the _.sorted index, where I pass in the sorted collection. Then I pass in the new guy, the thing to look up, and then the property I want to look it up on.
This will return an index of where I can put them into the sorted collection. If I like this index out and run it, you'll see that because we are looking this up by his name, his name being John, not the age, that he should be in the third position, which would put him right after Chris, because three is actually four in a zero based array.
I'll just say sortedcollection.splice. I want to add in this index. At this index, I won't remove anything, but I will add in the new guy. Then if I log out the sorted collection, you can see that John is in the proper spot. John, right here, is after Abe, Beth and Chris. If I want to add John by age, then I can just change the age in index lookup, and age in the sort by, and now you can see that John is in the proper spot by age, which is right after Beth, who is 33.
To recap here, the sort by works bypassing in the collection, and then the property you want to sort on. The sorted index works by passing in a collection, a new object that would fit in that collection, and then the property you want to look up that guy on. To add him in, you just say splice cap pass in that index you get back, say, "don't remove anything," and then the object that's actually going to get pushed in.