Jabri Juhinin
Jabri Juhinin

Reputation: 123

How can I get the highest number of votes in this array ? (React JS)

How can I get the highest number of votes in the following arrays ? I tried to have a look on the net including stackoverflow about how to find the highest value in an array and I tried applying it like this,

const sortHighestVotes = Math.max.apply(Math, votes.map(function(o) { return o.vote ; }))

I got no errors but the value displayed was NaN. I think that this is because of the attribute which is introduced in the handleVotes component. This is different from most of references that I referred to where attribute is already defined in a "key: value" pair in their array/object. A little bit different from my situation. The following are my code. How can I fix this ?

const App = () => {
  const handleClick2 = () => {
    setSelected(Math.floor(Math.random()*anecdotes.length))
  }

  const handleVotes = () => { 
    setVotes((votes) => 
      votes.map((vote, index) => index === selected ? vote + 1 : vote)
    )
  }

  const anecdotes = [
    'If it hurts, do it more often.',
    'Adding manpower to a late software project makes it later!',
    'The first 90 percent of the code accounts for the first 10 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.',
  ]
   
  const [selected, setSelected] = useState(0)
  const [votes, setVotes] = useState(() => Array(anecdotes.length).fill(0))

  const sortHighestVotes = Math.max.apply(Math, votes.map(function(o) { return o.vote ; }))

  return (

    <div style={inlineParagraph}>
      <h1>Anecdote of the day</h1>

      { anecdotes[selected] }

      <div style={inlineButton} >
        <Button handleClick={handleClick2} text="next anecdotes" setSelected={setSelected} />
        <Button handleClick={handleVotes} text="vote" setSelected={setSelected}/> : {votes[selected]}
      </div>

      <h1>Anecdote with the most votes</h1>
      <p> { sortHighestVotes }  </p> 
      
    </div>
  )
}

export default App

Upvotes: 1

Views: 318

Answers (1)

programandoconro
programandoconro

Reputation: 2709

Please try Math.max(...votes);. You need to spread the array to get each value, then Math.max will return you the highest value. Just be careful to check if the array exists and has numbers inside.

EDIT: If you want to find the index of the highest vote anectote. You can do:

 const maxVoteIndex = votes.indexOf(Math.max(...votes));
 const maxVoteAnecdote = anecdotes[maxVoteIndex];

Upvotes: 1

Related Questions