最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Finding the key of the max value in a javascript array - Stack Overflow

programmeradmin1浏览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?

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?

Share Improve this question asked Jul 3, 2012 at 19:18 Joey AugustinJoey Augustin 31 gold badge1 silver badge4 bronze badges 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]) – ZER0 Commented Jul 3, 2012 at 19:22
Add a ment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论