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! 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. The post data is stored in mongodb as shown in the picture below
Post.jsx
Code:
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))
)