I'm trying to sort an array of objects by the rate and alphabetical order.
So I sorted it by rate successfully. BUT THE PROBLEM is when I tried sorting it by alphabetical order, it doesn't work. I have no idea how to sort it again by alphabetical order.
The source code and the result is written at the bottom.
// This is the success result that I want to get **(sorted by rate && sorted by alphabetic order)**
{
abcd ( title)
lorem ipsum (comment)
5 (rate)
},
{
efg
lorem ipsum
5
},
{
bdg
lorem ipsum
3
},
{
def
lorem ipsum
3
},
{
abc
lorem ipsum
1
}
Source Code
const Reviews = ({ books, initialData }) => {
const combinedBooks = initialData.concat(books);
// sort by rate
let sorted = combinedBooks.sort((a, b) => {
return b.score - a.score;
});
// sort by alphabetical order
let newSorted = sorted.sort(function (a, b) {
let fa = a.title.toLowerCase(),
fb = b.title.toLowerCase();
if (fa < fb) {
return -1;
}
if (fa > fb) {
return 1;
}
return 0;
});
return (
<section style={{ border: "3px solid green" }}>
<Header title="Book Review Lists" />
{sorted.map((review) => {
const { id, title, comment, score } = review;
return (
<Review key={id} title={title} comment={comment} score={score} />
);
})}
</section>
);
};
export default Reviews;
//Code Result
{
abc
lorem ipsum
1
},
{
abcd
lorem ipsum
5
},
{
bdg
lorem ipsum
3
},
{
def
lorem ipsum
3
},
{
efg ( book title)
lorem ipsum ( book review )
5 (rate)
},