简体   繁体   中英

In JavaScript how would I create a variable to go through an array and remember not only the highest value but also the position of that value

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.

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

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM