'How can I sort my data based on ratings using react js

My database looks like this. I want to create a filter that will return top-rated data

{
_id:61f24397e8192a0a5994aaa8
title:"title"
expense:"50"
ratings:"5"
date:"2022-01-28"
time:"10"
category:"k"
location:"1010"
description:"101010"
}

I tried to like this but got an error Sidebar.js:14 Uncaught (in promise) TypeError: parseInt(...).sort is not a function

useEffect(() => {
        setIsLoading(true)
        fetch(`http://localhost:5000/blogs`)
            .then(res => res.json())
            .then(data => {
                const approvedBlogs = data.filter(blogs => parseInt(blogs.ratings).sort((a, b) => b - a))
                // const approvedBlogs = data.filter(blogs => blogs.ratings === '5')
                setBlogs(approvedBlogs)
            })
            .finally(() => setIsLoading(false))
    }, [])


Solution 1:[1]

It's true that you're are trying to sort an integer instead of an array.

Change this line:

 const approvedBlogs = data.filter(blogs => parseInt(blogs.ratings).sort((a, b) => b - a))

To this:

const approvedBlogs = data.sort((a, b) => (+a.ratings > +b.ratings ? -1 : 1));

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Solution 2:[2]

You can use .filter to throw away blogs you don't want anymore (like in commented line). After that, use .sort to order data by ratings. It should look like:

const approvedBlogs = data.filter(blogs => blogs.ratings === '5')
                           .sort( (a, b) => return parseInt(b.rating) - parseInt(a.rating)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 amlxv
Solution 2 Dominik Misiek