如何在对象数组中获得最大值的索引

How to get index of the max value in array of objects?

本文关键字:最大值 索引 对象 数组      更新时间:2023-09-26

我有一个数组,格式如下:

var dataset = [{
    date: '1',
    value: '55'
}, {
    date: '2',
    value: '52'
}, {
    date: '3',
    value: '47'
}];

我通过

得到它的最大值
var maxValue = Math.max.apply(Math, dataset.map(function(o) {
    return o.value;
}));

效果很好,没什么好担心的。但是我怎样才能获得maxValue的索引呢?

我试过indexOf()(它一直返回我-1),jQuery inArray()以及reduce(),但它们都不能正常工作。

我想有一种更简洁的方法,通过迭代所有元素来获得索引。

作为Array.forEach的替代品

var dataset = [{date:'1',value:'55'},{date:'2',value:'56'},{date:'3',value:'47'}],
    max = -Infinity,
    key;  
dataset.forEach(function (v, k) { 
    if (max < +v.value) { 
        max = +v.value; 
        key = k; 
    }
});
console.log(key);
console.log(dataset[key]);

您可以使用Array.mp()创建的temp数组来查找像

这样的索引

var dataset = [{
  date: '1',
  value: '55'
}, {
  date: '2',
  value: '59'
}, {
  date: '3',
  value: '47'
}];
var tmp = dataset.map(function(o) {
  return o.value;
});
var maxValue = Math.max.apply(Math, tmp);
//find the index using the tmp array, need to convert maxValue to a string since value is of type string
var index = tmp.indexOf(maxValue + '');
snippet.log(maxValue + ' : ' + index)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>