在数组的数组中找到最小的数字
find the smallest number in a array of an array
我正在尝试编写一个函数来查找数组的数组中的最小数字。
已经尝试过了,但我真的不知道当数组上有数组时该怎么做。
const arr = [4, 8, 2, 7, 6, 42, 41, 77, 32, 9]
const min = Math.min(arr)
console.log(min)
通过使用 ES6,您可以使用 spread syntax ...
,它将数组作为参数。
const arr = [4, 8, 2, 7, 6, 42, 41, 77, 32, 9];
const min = Math.min(...arr);
console.log(min);
使用 ES5,您可以将 Function#apply
, which take this
和参数作为数组。
const arr = [4, 8, 2, 7, 6, 42, 41, 77, 32, 9];
const min = Math.min.apply(null, arr);
console.log(min);
对于非扁平数组,采用扁平化函数,例如
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);
您可以对每个使用 map
to iterate over the nested arrays and then use Math.min(...array)
以获得最小值。 map
的输出是一个最小值数组。
const arr = [[4, 8, 2], [7, 6, 42], [41, 77, 32, 9]];
const out = arr.map(a => Math.min(...a));
console.log(out);
使用传播 ...
和 flat
:
const a = [[0, 45, 2], [3, 6, 2], [1, 5, 9]];
console.log(Math.min(...a.flat()));
或者您可以使用 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);
我正在尝试编写一个函数来查找数组的数组中的最小数字。
已经尝试过了,但我真的不知道当数组上有数组时该怎么做。
const arr = [4, 8, 2, 7, 6, 42, 41, 77, 32, 9]
const min = Math.min(arr)
console.log(min)
通过使用 ES6,您可以使用 spread syntax ...
,它将数组作为参数。
const arr = [4, 8, 2, 7, 6, 42, 41, 77, 32, 9];
const min = Math.min(...arr);
console.log(min);
使用 ES5,您可以将 Function#apply
, which take this
和参数作为数组。
const arr = [4, 8, 2, 7, 6, 42, 41, 77, 32, 9];
const min = Math.min.apply(null, arr);
console.log(min);
对于非扁平数组,采用扁平化函数,例如
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);
您可以对每个使用 map
to iterate over the nested arrays and then use Math.min(...array)
以获得最小值。 map
的输出是一个最小值数组。
const arr = [[4, 8, 2], [7, 6, 42], [41, 77, 32, 9]];
const out = arr.map(a => Math.min(...a));
console.log(out);
使用传播 ...
和 flat
:
const a = [[0, 45, 2], [3, 6, 2], [1, 5, 9]];
console.log(Math.min(...a.flat()));
或者您可以使用 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);