0

Hello I have been trying to find the highest value in my constantly changing array. What I need is to have an array that changes acording to input (which I have) and a table that shows the three highest values of that array and changes along with the array values. I used the Math.max, but I always get NaN as my answer. This is my code:

   const array = [
    Weighted1,
    Weighted2,
    Weighted3,
    Weighted4,
    Weighted5,
    Weighted6,
    Weighted7,
    Weighted8,
    Weighted9,
    Weighted10,
    Weighted11,
    Weighted12,
  ];

  const [First, setFirst] = useState("");
  const [Second, setSecond] = useState("");
  const [Third, setThird] = useState("");
 
  /*
  useEffect(() => {
    setFirst(Math.max(array));
  }, [array]);
  useEffect(() => {
    setSecond(array.splice(array.indexOf(one), 1), Math.max(array));
  }, [array, one]);
  useEffect(() => {
    setThird(array.splice(array.indexOf(Second), 1));
  }, [array, Second]);
*/

Mytable has these two tipes of values, one is the weighted (all those zeros) and the other is the names I want to be displayed depending on the weighted next to it. enter image description here

1
  • Math.max(...array), I think. Commented Feb 8, 2022 at 11:24

1 Answer 1

1

You can use your useEffect() to listens to the changing input and sort the array via: Array.sort(). After this you can set your use last 3 items in that array as your values.

  useEffect(() => {
    const sortedArray = yourInputArray.sort();
    setFirst(sortedArray[sortedArray.length - 1])
    setSecond(sortedArray[sortedArray.length - 2])
    setThird(sortedArray[sortedArray.length - 3])
  }, [yourInputArray]);

A better approach would be storing your input values as a sorted array and using that directly in the component.

const [sortedArray, setSortedArray] = useState();

useEffect(() => {
  setSortedArray(yourInputArray.sort());
}, [yourInputArray]);

{sortedArray && (
  <>
    <p>1: {sortedArray[sortedArray.length - 1]}</p>
    <p>2: {sortedArray[sortedArray.length - 2]}</p>
    <p>3: {sortedArray[sortedArray.length - 3]}</p>
  <>
)}
Sign up to request clarification or add additional context in comments.

11 Comments

Glad it helped.
And please note that the first solution was to illustrate how you can 1 useEffect to handle several operations at once. It is not good practice.
The second solution is a better example of how you can think about the data that you store.
It aims to keep it simple: receive data => sort the data in the right order => store that data in a useState => use that useState variable to display UI
With this approach there is a single source of truth. Your data is the sorted array and the UI displays that data.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.