0

I have an empty array into which I am pushing values using javascript. I am able to find the max value of the array and set that to a variable using the following:

Array.max = function( array ){
 return Math.max.apply( Math, array );
};
var maxX = Array.max(xArray);

How can I find the key associated with that value?

asked Jul 3, 2012 at 19:18
1
  • 1
    You mean, the index? And what should be the logic if multiple indexes have the maximum value? (e.g. [1, 4, 2, 4]) Commented Jul 3, 2012 at 19:22

1 Answer 1

4

Assuming that the values are unique, you could use Array.indexOf:

var maxX = Array.max(xArray);
var index = xArray.indexOf(maxX);

If the keys are not unique, index will contain the key of the first element found. If the value does not exist at all, the "key" will be -1.

answered Jul 3, 2012 at 19:20

2 Comments

Array.max() is not even an existing function, I believe you meant Math.max.apply()
for me I had to spread my array inside Math.max like Math.max(...[1, 2, 3])

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.