Alright, let's break that down...
sortedArticles(): Article[] {
return this.articles.sort((a: Article, b: Article) => b.votes - a.votes);
}
(a: Article, b: Article) => b.votes - a.votes
- This function is similar to
function(a, b) { return b.votes - a.votes }
. It ensures the correct sorting order for the array elements by comparing their vote counts. If the first article (
a
) has more votes, it will result in a negative value; if both have equal votes, it will be
0
; if the second article (
b
) has more votes, it will give a positive number.
some_array.sort()
requires a function as input. It can be either named or anonymous like here. The function assesses pairs of elements in the array to determine whether they should swap positions or remain unchanged. A negative value means the first element comes before the second, while a positive value indicates the opposite. When the function returns 0
, the elements are considered equal and usually retain their original order during sorting.
Therefore, invoking sortedArticles()
will yield a list of articles arranged based on their respective "votes".