在对象数组中查找最大值 [英] Find max value in object array
问题描述
我有一个看起来像这样的对象:
I have object that looks like this:
peaks =
0: {intervalId: 7, time: 1520290800000, value: 54.95125000000001}
1: {intervalId: 7, time: 1520377200000, value: 49.01083333333333}
以此类推.
如何查找具有 Max
值的 peak
?我试图这样做
How do I find peak
that has Max
value?
I tried to do it like this
this.loadPeak = peaks.map(a => Math.max(a.value));
但我只是得到了带有 value
(而不是所有intervalId,time,value)而不是最大值的一堆峰阵列.
but I just got bunch of peaks array with value
(instead of all intervalId, time, value) and not the max value.
**非常感谢大家,每个解决方案都在起作用,可悲的是不能接受所有解决方案.**
**Thank you so much for everyone, every solution was working, sadly can't accept all. **
推荐答案
对数组进行排序的主要问题是,它会导致遍历数组的许多不必要的迭代.数组越大,该速度就越慢,进行排序以尝试上下移动元素.使用 reduce()
,我们可以以所需的最少步骤来处理此问题,如果当前元素的值大于上一个值,则只需替换上一个值即可:
The main issue with sorting your array, is it causes many needless iterations through your array. This gets drastically slower the bigger your array is, sorting to try and move elements up and down. With reduce()
, we can handle this in the minimum amount of steps needed, simply replacing the previous value if the current element's value is greater than the previous:
var peaks = [
{intervalId: 7, time: 1520290800000, value: 54.95125000000001},
{intervalId: 7, time: 1520377200000, value: 49.01083333333333}
];
const maxPeak = peaks.reduce((p, c) => p.value > c.value ? p : c);
console.log(maxPeak);
这篇关于在对象数组中查找最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!