0

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)
fryx
  • 29
  • 4
  • You want the smallest number per array (`[[1,2],[3,4]] -> [1,3]`), or all of them (`[[1,2],[3,4]] -> 1`)? – Andreas Jan 19 '19 at 16:19
  • the smallest number of all of them – fryx Jan 19 '19 at 16:28
  • 1
    You should add this information, and an example of a real input (array of arrays) in the question. I'm pretty sure @Andy would have posted a different answer if this would have been part of the question from the beginning. – Andreas Jan 19 '19 at 16:31
  • He certainly would have. – Andy Jan 19 '19 at 16:41

3 Answers3

4

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

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);
Andy
  • 61,948
  • 13
  • 68
  • 95
0

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);
Kosh
  • 16,966
  • 2
  • 19
  • 34