We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
WHY ALL THE TEST CASES ARE FAILING FOR THIS SOLUTION
import "h8k-components";
import Articles from "./components/Articles";
import { useState, useEffect } from "react";
import "./App.css";
// State for sorted articles
const [sortedArticles, setSortedArticles] = useState([]);
useEffect(() => {
// Ensure initial articles are sorted correctly by upvotes
if (articles.length) {
setSortedArticles([...articles].sort((a, b) => b.upvotes - a.upvotes));
}
}, [articles]);
const handleMostUpvoted = () => {
console.log("🔼 Sorting by upvotes...");
setSortedArticles([...articles].sort((a, b) => b.upvotes - a.upvotes));
};
const handleMostRecent = () => {
console.log("📅 Sorting by date...");
setSortedArticles([...articles].sort((a, b) => new Date(b.date) - new Date(a.date)));
};
return (
<>
Sort By
Most Upvoted
Most Recent
);
}
export default App;
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Article Sorting
You are viewing a single comment's thread. Return to all comments →
WHY ALL THE TEST CASES ARE FAILING FOR THIS SOLUTION import "h8k-components"; import Articles from "./components/Articles"; import { useState, useEffect } from "react"; import "./App.css";
function App({ articles }) { console.log("🔍 Initial Articles:", articles); // Debugging
// State for sorted articles const [sortedArticles, setSortedArticles] = useState([]);
useEffect(() => { // Ensure initial articles are sorted correctly by upvotes if (articles.length) { setSortedArticles([...articles].sort((a, b) => b.upvotes - a.upvotes)); } }, [articles]);
const handleMostUpvoted = () => { console.log("🔼 Sorting by upvotes..."); setSortedArticles([...articles].sort((a, b) => b.upvotes - a.upvotes)); };
const handleMostRecent = () => { console.log("📅 Sorting by date..."); setSortedArticles([...articles].sort((a, b) => new Date(b.date) - new Date(a.date))); };
return ( <> Sort By Most Upvoted Most Recent ); }
export default App;