我有一个这样的数组,并希望找到最大值的索引。对于这个样本,它应该返回c1:
PowerMockito.mockStatic(AppEntityManager.class);
PowerMockito.when(AppEntityManager.createEntityManager()).thenReturn(emMock);
答案 0 :(得分:2)
var arr=[{val: 9, x: 2, y: 0},
{val: 1, x: 3, y: 0},
{val: 6, x: 4, y: 0}
];
var max_value = arr.reduce((a,b)=> (a.x+a.y+a.val) > (b.x+b.y+b.val) ? a:b )
// or if it is the index that you want :
var max_index = arr.reduce((a,b,i,_)=> (_[a].x+_[a].y+_[a].val) > (b.x+b.y+b.val) ? a:i, 0);
console.log(max_value);
console.log(max_index);
答案 1 :(得分:0)
假设你的阵列是
var arr = [
{val: 9, x: 2, y: 0}, {val: 1, x: 3, y: 0}, {val: 6, x: 4, y: 0},
];
您可以使用Math.max.apply
和map
var output = Math.max.apply( null, arr.map( c => c.val ) )
或者,如果它是对象(根据您的最新更新)
var arr = {
c1:{val: 9, x: 2, y: 0},
c2:{val: 1, x: 3, y: 0},
c3:{val: 6, x: 4, y: 0}
};
var maxValue = Math.max.apply( null, Object.values( arr ).map( c => c.val ) )
您可以通过
获取maxValue
的索引
var output = Object.keys(arr).findIndex( s => arr[s].val == maxValue );