简体   繁体   中英

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. 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. But if you don't care about that you totally should use reduce like it is said below.

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 . Also, those functions has a time complexity of O(n) so with larger arrays it will work faster.


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)).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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