Home > Net >  How can I sort my data based on ratings using react js
How can I sort my data based on ratings using react js

Time:01-28

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))
    }, [])

CodePudding user response:

You can directly sort data without filtering

useEffect(() => {
        setIsLoading(true)
        fetch(`http://localhost:5000/blogs`)
            .then(res => res.json())
            .then(data => {
                 data.sort((a, b) => {
                     const parsedA = parseInt(a.ratings, 10);
                     const parsedB = parseInt(b.ratings, 10);
                     return parsedA > parsedB ? -1 : 1; // for descending sort inverse -1 and 1
                 });
                setBlogs(data)
            })
            .finally(() => setIsLoading(false))
    }, [])

CodePudding user response:

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

CodePudding user response:

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)
  •  Tags:  
  • Related