Anthony Davis Anthony Davis - 1 month ago 8
TypeScript Question

Don't understand: "sort((a: Article, b: Article) => b.votes - a.votes);"

I am not understanding the return statement in sortedArticles(). Can somone point me to a link, or explain how this sort function work?

sortedArticles(): Article[] {
return this.articles.sort((a: Article, b: Article) => b.votes - a.votes);
}





<div class="ui grid posts">
<app-article
*ngFor="let article of sortedArticles()"
[article]="article">
</app-article>
</div>


May be a trivial question, but for some reason could not find the answer online. Appreciate the help.

Answer

Okay, let's break that down for you...

sortedArticles(): Article[] {
    return this.articles.sort((a: Article, b: Article) => b.votes - a.votes);
}

(a: Article, b: Article) => b.votes - a.votes - This is equivalent to function(a, b) { return b.votes - a.votes }, and will return the proper values in order for sort() to be able to re-order the array elements. If the first article (a) has more votes, it'll return a negative value; if both articles have the same number of votes, it'll return 0; if the second article (b) has more votes, it'll return a positive number.

some_array.sort() takes a function as its parameter. This can be a named function, or an anonymous function like is done here. It'll loop through the array and pass in two elements into the function to determine if they should be swapped or stay in that order. If the function returns a negative value, the first item should go before the second; if the function returns a positive value, the second item should go before the first; if the function returns 0, then they're equally weighted, and their order doesn't matter -- the sort() usually puts them in their original order in this case.

So, calling sortedArticles() will return a list of articles, ordered by how many "votes" they each have.