The application has cards, each of which stores a number. I need to sort array by these numbers so that the application is re-rendered and the cards should be rendered from lowest numbers to highest numbers.
Code below:
App.js:
// array of numbers
const [cardsList, setCardsList] = React.useState([]);
// function to generate random numbers
const generateNumber = (maxNumber = 100) => {
let random = Math.random() * maxNumber;
return random;
};
// function to add cards to the card list
const addCard = () => {
let num = Math.floor(generateNumber());
setCardsList((prev) => [...prev, num]);
};
// function that need to sort cards
const sortCards = () => {};
CardList.js:
// cards rendering
<div className="cardList">
{props.cardList.map((number) => {
return (
<div className="card" key={number}>
<div className="card-close">
<img
style={{ cursor: "pointer" }}
width={16}
height={16}
src="/img/delete.png"
alt="closeBtn"
/>
</div>
<h1>{number}</h1>
</div>
);
})}
</div>
CodePudding user response:
Have you tried .sort method?
in your case will be something like that:
const sortedCards = cardList.sort((a,b) => a.number > b.number)
CodePudding user response:
// Please look into the below link
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
// You can try this with the general sort function.
const sortCards = () => {
if( cardsList.length > 0 ){
return cardsList.sort();
}
return -1;
};