-5
var array = [1,2,3,4,5];
for(i = 0; i < array.length; i ++){

}

This is how far I have understood it (not my actual code just an example) and how would I use this for loop to go through the array and then not only remember the highest value but also the position that it is in. What I want to do specifically in my code is create a point system that increases the values of different position numbers in the array, then sorts through them to find the highest value and depending on which position/variable in the array has the highest value it will do something different. apologies for the grammar.

  • So in short, are you trying to get the highest value and the index as well? From the example its `index 4` and the value is `5` – Kopi Bryant Mar 25 '21 at 02:12
  • https://stackoverflow.com/questions/11301438/return-index-of-greatest-value-in-an-array/11301464 –  Mar 25 '21 at 02:12

2 Answers2

0

You could write a function that keeps track of the index with the highest value, max, and update it whenever arr[i] is greater -

function goThroughAnArrayAndRememberNotOnlyTheHighestValueButAlsoThePositionOfThatValue(arr)
{ if (arr.length == 0) return false
  let max = 0
  for (let i = 1; i < arr.length; i++)
    if (arr[i] > arr[max])
      max = i
  return { highestValue: arr[max], positionOfThatValue: max }
}

const input1 =
  [ 1, 6, 4, 3, 9, 5, 8, 7 ]
  
const input2 =
  []

console.log(goThroughAnArrayAndRememberNotOnlyTheHighestValueButAlsoThePositionOfThatValue(input1))
// { highestValue: 9, positionOfThatValue: 4 }

console.log(goThroughAnArrayAndRememberNotOnlyTheHighestValueButAlsoThePositionOfThatValue(input2))
// false
Mulan
  • 129,518
  • 31
  • 228
  • 259
0

simply use an array.reduce method

var myArray = [0,1,2,12,3,4,5]
 
const f_MaxPos = arr => arr.reduce((r,c,i)=>
  {
  if (!i || c > r.max)
    {
    r.max = c 
    r.pos = i
    } 
  return r
  }, { max:undefined, pos:-1 })
 

console.log( JSON.stringify( f_MaxPos( myArray ) ) )
 
.as-console-wrapper {max-height: 100%!important;top:0}
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40