简体   繁体   中英

find the smallest number in a array of an array

i'm trying to write a function to find the smallest number on an array of an array.

already tryed this, but i don't really know how to do when there is arrays on an array.

 const arr = [4, 8, 2, 7, 6, 42, 41, 77, 32, 9] const min = Math.min(arr) console.log(min) 

By taking ES6, you could use the spread syntax ... , which takes an array as arguments.

 const arr = [4, 8, 2, 7, 6, 42, 41, 77, 32, 9]; const min = Math.min(...arr); console.log(min); 

With ES5, you could take Function#apply , which take this and the parameters as array.

 const arr = [4, 8, 2, 7, 6, 42, 41, 77, 32, 9]; const min = Math.min.apply(null, arr); console.log(min); 

For unflat arrays, take a flatten function, like

 const flat = array => array.reduce((r, a) => r.concat(Array.isArray(a) ? flat(a) : a), []), array = [[1, 2], [3, 4]], min = Math.min(...flat(array)); console.log(min); 

You can use map to iterate over the nested arrays and then use Math.min(...array) on each to get the minimum. The output from map is an array of minimum values.

 const arr = [[4, 8, 2], [7, 6, 42], [41, 77, 32, 9]]; const out = arr.map(a => Math.min(...a)); console.log(out); 

Use spread ... and flat :

 const a = [[0, 45, 2], [3, 6, 2], [1, 5, 9]]; console.log(Math.min(...a.flat())); 

Or you might use reduce :

 const arr = [[7, 45, 2], [3, 6, 2], [1, 5, 9]]; let r = arr.reduce((a, e) => Math.min(a, ...e), Infinity) console.log(r); 

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