7 days of WordPress plugins, themes & templates - for free! Unlimited asset downloads! Start 7-Day Free Trial
FREELessons: 28Length: 4 hours

• Overview
• Transcript

4.12 Sorting Stores

Right now, our stores don't sort their content at all. We'll correct that in this lesson.

5.Conclusion1 lesson, 00:29

4.12 Sorting Stores

At the end of our last video, we saw that we could successfully follow a new user and have their Chirps show up in our timeline. However, these Chirps are not actually showing up in the order that we'd like. We would like the most recent Chirp to show up at the top. So we need to sort our Chirp store by date. This is actually pretty easy to do. We're here in our store constructor file, that's in the source directory inside the stores directory in the store.js file, and in the store method object, we want to add a sort method. So right underneath add here, let's add a method called sort. And we're just going to make sorting by date the default for all of our stores. So within this we can say this._data and then we can call JavaScript's sort method. And we're going to pass this a function, a comparator function, that takes two parameters, a and b. And of course a and b will be two of our Chirps, or users whichever one we're happening to sort. And we need to decide which one will go first. Now it's actually really, really easy to do. We can just first, convert their created properties from a string date into an actual date object. So we can say new date and then we can say a.$created and this gives us an actual date object. But now, if we put a unary + operator in front of this date object, it converts this date object into a number, a Unix timestamp. So then, what we can do is just subtract the time of b from the time of a and that will return either a positive or a negative number. And if it's a positive number I think a will go first and if it's a negative number b will go first. So we'll have new date, b.$created. And let's just return this and this is all we need to do to create our sort function. However, we do need to call it. Let's call it in two places. First we'll call it inside set, right at the end we can say this.sort to sort our data, and then let's also call it every time we add an item to a store. So we'll say this.sort in our add function here. That should really be all we need to do. Now, if we come back to our home page and refresh it, you can see that our Chirps are actually showing up in the correct order. So, that was sorting our collections. Very simple, but it does exactly what we want.

Back to the top