简体   繁体   English

在数组数组中查找最大/最小元素的最有效方法

[英]Most efficient way to find max/min element in array of array

I'd like to know how Can I return the min/max element in array of array Efficiently. 我想知道如何才能有效地返回数组array中的min / max元素。 I know I can do a loop throught the array but I think there may be a better option. 我知道我可以遍历整个数组,但是我认为可能会有更好的选择。

let tab= [2];
tab[0] = [{name :"book", value : 8}, {name :"cake", value : 2}]
tab[1] ... etc

I want to find the min or max value in this array for example. 我想例如在此数组中找到最小值或最大值。

I go with Math.max.apply to do that since it's referencing the array while reduce duplicates it. 我使用Math.max.apply来执行此操作,因为它引用数组,同时减少重复数组。 But if you don't care about that you totally should use reduce like it is said below. 但是,如果您不在乎,则应完全使用reduce,如下所述。

There are many ways of doing it. 有很多方法可以做到这一点。 The first one is to reduce the array maintaining the max/min value: 第一个是减少保持最大/最小值的数组:

 let tab= [2]; tab[0] = [{name :"book", value : 8}, {name :"cake", value : 2}] tab[1] = [{name :"apple", value : 1}, {name :"spaceship", value : 200}] console.log( tab.map(a=>a.reduce((a,b)=>a.value>b.value?a:b,{})).reduce((a,b)=>a.value>b.value?a:b,{}) ) 

This can be easier if we flatten the array as follow 如果我们按以下方式展平数组,这会更容易

 let tab= [2]; tab[0] = [{name :"book", value : 8}, {name :"cake", value : 2}] tab[1] = [{name :"apple", value : 1}, {name :"spaceship", value : 200}] console.log( [].concat.apply([], tab).reduce((a,b)=>a.value>b.value?a:b,{}) ) 

Those above functions get the max value, to get the min simply change a.value>b.value to a.value<b.value . 上面的那些函数获取最大值,要获取最小值,只需将a.value>b.value更改为a.value>b.value a.value<b.value Also, those functions has a time complexity of O(n) so with larger arrays it will work faster. 而且,这些函数的时间复杂度为O(n)因此对于较大的数组,它将更快地工作。


The other way is to sort and get the first/last value 另一种方法是排序并获得第一个/最后一个值

 let tab= [2]; tab[0] = [{name :"book", value : 8}, {name :"cake", value : 2}] tab[1] = [{name :"apple", value : 1}, {name :"spaceship", value : 200}] console.log( [].concat.apply([], tab).sort((a,b)=>b.value-a.value)[0] ) 

However this method is more complex as it sorts the array first (O(n log n)) and then gets the first or last element (O(1)). 但是,此方法更为复杂,因为它先对数组排序(O(n log n)),然后再获取第一个或最后一个元素(O(1))。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM