如何获得单个数组中具有最大差异的元素? [英] How to get the elements with maximum difference in the single array?
本文介绍了如何获得单个数组中具有最大差异的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设a = [3,7,8,66,121,223,228]如何获得其中最大差异的元素? 我对此有解决方案,但是会比这更好的代码.
Suppose, a= [3,7, 8,66,121,223,228] how to get the elements with maximum difference among them? I have this solution to it but will appreciate better code than this.
let arr = []
a.sort((a,b)=>{
return arr.push(a-b)
})
let index = arr.indexOf(Math.max(...arr))
a.sort((a,b)=> a-b).slice(index,index+2)
我希望输出为[121,223]
I expect the output to be [121,223]
推荐答案
您可以检查每对具有最后发现对的对,并获得具有最大增量的对.
You could check each pair with the last found pair and get the one with the greatest delta.
var array = [3, 7, 8, 66, 121, 223, 228],
result = array.reduce((r, b, i, { [i - 1]: a }) => {
if (i === 0) return;
if (i === 1 || b - a > r[1] - r[0]) return [a, b];
return r;
}, undefined);
console.log(result);
这篇关于如何获得单个数组中具有最大差异的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文