如何获取对象数组中最大值的索引?

时间:2021-05-20 22:57:43

I've got an array with following format:

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

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

And I'm getting the maximum value in it by:

我通过以下方式获得最大值:

var maxValue = Math.max.apply(Math, dataset.map(function(o) {
    return o.value;
}));

It works very well, there's nothing to worry about. But how I can obtain an index of the maxValue?

它工作得很好,没有什么可担心的。但我如何获得maxValue的索引?

I've tried indexOf() (which returns me -1 all the time), jQuery inArray() as well as reduce() but none of them work properly.

我已经尝试过indexOf()(它一直返回-1),jQuery inArray()以及reduce()但它们都没有正常工作。

I guess there's a more cleaner way by iterating all elements to get the index.

我想通过迭代所有元素来获得索引有更清晰的方法。

Thanks in advance.

提前致谢。

2 个解决方案

#1


2  

As an alternative with Array.forEach

作为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]);

#2


2  

You can use the temp array created by Array.mp() to find the index like

您可以使用Array.mp()创建的临时数组来查找索引

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>

#1


2  

As an alternative with Array.forEach

作为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]);

#2


2  

You can use the temp array created by Array.mp() to find the index like

您可以使用Array.mp()创建的临时数组来查找索引

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>