Reputation: 51
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
Upvotes: 3
Views: 3676
Reputation: 156
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.
Upvotes: 0
Reputation: 66490
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]);
Upvotes: 2
Reputation: 40318
var array1 = dan, john, james, harry, mike;
Array.max = function( array ){
return array1.indexOf(Math.max.apply( Math, array ));
};
Upvotes: 0
Reputation: 236022
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.
Upvotes: 5