简体   繁体   English

如何对一系列帖子进行排序

[英]How to sort an array of posts

I want to sort an array of posts by createdAt dates, now the posts are sorting by first the oldest one then the new one, but I want to be sorted the opposite way!我想按 createdAt 日期对一组帖子进行排序,现在帖子首先按最旧的帖子排序,然后是新的帖子,但我想以相反的方式排序! already tried .sort((a, b) => b.createdAt - a.createdAt) but didn't work, I'm not sure if it's the way to implement it.已经尝试过.sort((a, b) => b.createdAt - a.createdAt)但没有用,我不确定这是否是实现它的方式。 The post data is stored in mongodb as shown in the picture below post数据存放在mongodb如下图

Posts Model:帖子 Model: 在此处输入图像描述

Post.jsx Code: Post.jsx代码:

export default function Posts({ posts = [] }) {

    const [filteredResults, setFilteredResults] = useState([]);
    const [searchInput, setSearchInput] = useState('');
    const [isLoading, setIsLoading] = useState(false);
  
    const filter = (e) => {
      const keyword = e.target.value;
  
        if (keyword !== '') {
            const filteredData = posts.filter((post) => {
                return Object.values(post)
                .join('')
                .toLowerCase()
                .includes(searchInput.toLowerCase())
            })
            setFilteredResults(filteredData)
            
        } else {
          setFilteredResults(posts)
        }
  
        setSearchInput(keyword);
    }
    console.log(filteredResults)

  return (
    <div className="posts">
      <div className="postsContainer">

      <div className="postsSearchContainer">
            <div className="postsSearch">
                  <div class="postsSearchIconContainer">
                      <SearchIcon class="w-5 h-5" />
                  </div>
                    <input type="text"
                    className="postsSearchInput"
                    placeholder="بحث"
                    name="postsSearchText"
                    id="postsSearchText"
                    onChange={filter}
                    />
              </div>
              {/* ENDS OF POSTSSEARCHCONTAINER */}
      </div>
      {/* ENDS OF POSTSSEARCH */}
    <div className="postsBoxContainer">
      <div className="postsBox">
      {isLoading ? (
          <Box sx={{ display: 'flex' }}>
            <CircularProgress />
          </Box>
      ) : (
        filteredResults.length > 0 ? (
          filteredResults.map((p) => (
            <Post post={p} />
          ))
          ) : (posts.map((p) => (
            <Post post={p} />
          ))
        )
        }
      </div>
      </div>
      {/* ENDS OF POSTSBOX */}

      </div>
      {/* ENDS OF POSTCONTAINER */}

    </div>
    //ENDS OF POSTS

  );
};

The Code I tried:

(
        filteredResults.length > 0 ? (
          filteredResults.map((p) => (
            <Post post={p} />
          )).sort((a, b) => b.createdAt - a.createdAt)
          ) : (posts.map((p) => (
            <Post post={p} />
          )).sort((a, b) => b.createdAt - a.createdAt))
        )

convert your dates strings into timestamps (in case they are all ready a date object just use the getTime()将您的日期字符串转换为时间戳(如果它们都准备好日期 object 只需使用 getTime()

sort((a, b) => new Date(b.createdAt).getTime()  - new Date(a.createdAt).getTime() )

Solution解决方案

 filteredResults.length > 0 ? (
          filteredResults.map((p) => (
            <Post post={p} />
          )).sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
          ) : (posts.map((p) => (
            <Post post={p} />
          )).sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt)))
        )

 //example const data = [ "2022-11-17T17:51:45.537+00:00", "2022-11-17T17:51:45.539+00:00", "2022-11-16T18:51:45.537+00:00", "2022-11-15T17:51:45.537+00:00", "2022-11-16T17:51:45.537+00:00" ] console.log(data.sort((a, b) => new Date(b) - new Date(a)));

I guess you may want to sort first then map over it because you are returning component's from map and then trying to sort them which is not intented to be if I'm not wrong here...我猜你可能想先对它进行排序,然后对它进行 map 排序,因为你要从 map 返回组件,然后尝试对它们进行排序,如果我没记错的话,这不是故意的......

As sort does sorting the array in place (mutates original array) you might want to have the copy and sort it.正如sort对数组进行就地排序(改变原始数组)一样,您可能希望获得副本并对其进行排序。

for eg [... your_data].sort((a,b)=>....).map(p => <Post post={p} />)例如[... your_data].sort((a,b)=>....).map(p => <Post post={p} />)

you can take the approaches of sorting time from the other answers suggested here...您可以从此处建议的其他答案中采用排序时间的方法...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM