0

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>
0

2 Answers 2

0

Have you tried .sort method?

in your case will be something like that:

const sortedCards = cardList.sort((a,b) => a.number > b.number) 
Sign up to request clarification or add additional context in comments.

2 Comments

I tried it, but my react app doesn't re-rendering after that.
array.sort((a, b)=> a - b ) is the correct way to sort numbers
0
// 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;
        };
       

3 Comments

I tried it, but it doesn't work correctly. I had an array like [15, 34, 4, 144], and .sort method returns me this array: [144, 15, 34, 4], because it's sorting only by first integer, '1' from '15', '3' from '34', '4' from '4', '1' from '144'
share your code here so I can look into it ..
and also pls clear me that do u want to sort asc or Desc order .

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.