Javascript max value of array and find where it is? - Stack Overflow

javascript question here...I need to find the highest number in an array and then return where in the a

javascript question here...

I need to find the highest number in an array and then return where in the array this number is. It cannot be sorted as this needs to match up with a word in another array. Heres the array:

var array1 = dan, john, james, harry, mike;
var array2 = 66, 33, 85, 34, 45;

Basically the number must match up with the name its already with. If anyone has the answer I would be most happy :)

Thanks

javascript question here...

I need to find the highest number in an array and then return where in the array this number is. It cannot be sorted as this needs to match up with a word in another array. Heres the array:

var array1 = dan, john, james, harry, mike;
var array2 = 66, 33, 85, 34, 45;

Basically the number must match up with the name its already with. If anyone has the answer I would be most happy :)

Thanks

Share Improve this question asked Mar 11, 2013 at 11:04 Daniel BowenDaniel Bowen 672 silver badges9 bronze badges 3
  • Are these numbers unique? – VisioN Commented Mar 11, 2013 at 11:06
  • 2 ...if not just implement your own "for" cycle where you search for the maximum (and you store its index too). – Adriano Repetti Commented Mar 11, 2013 at 11:06
  • Take a look here, I think this will resolve your problem =) stackoverflow./questions/5850956/… – Crowlix Commented Mar 11, 2013 at 11:08
Add a ment  | 

4 Answers 4

Reset to default 5
var array1    = [ 'dan', 'john', 'james', 'harry', 'mike' ],
    array2    = [ 66, 33, 85, 34, 45 ],
    maxPos    = Math.max.apply( null, array2 ),
    posInArr  = array2.indexOf( maxPos );

console.log( array1[ posInArr ] );  // 'james'

The above code demonstrates the usage of Math.max() and Array.prototype.indexOf() to get the highest number within array2 and then find the index of that number in that array.

here is search script:

var array1 = ['dan', 'john', 'james', 'harry', 'mike'];
var array2 = [66, 33, 85, 34, 45];
var max = array2.length-1;
for (var i=array2.length-1; i--;) {
   if (array2[i] > array[max]) {
      max = i;
   }
}
alert(array1[max]);
   var array1 = dan, john, james, harry, mike;


  Array.max = function( array ){
        return array1.indexOf(Math.max.apply( Math, array ));
    };

You can read your array into a loop. If the number read is higher than the previous one, store it into a variable, with a second variable for its index.

At the end you'll have the max of your array and its index.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742281505a4414573.html

相关推荐

  • Javascript max value of array and find where it is? - Stack Overflow

    javascript question here...I need to find the highest number in an array and then return where in the a

    21小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信