Green Cat
Green Cat

Reputation: 1

React find 3 highest values in an array

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

Upvotes: 0

Views: 512

Answers (1)

jolo
jolo

Reputation: 660

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>
  <>
)}

Upvotes: 1

Related Questions