返回JavaScript中数组的最小值和最大值的函数
问题
我们需要编写一个接受一个数组并返回另一个数组的JavaScript函数,该数组的第一个元素应该是输入数组的最小元素,第二个应该是输入数组的最大元素。
示例
以下是代码-
const arr = [56, 34, 23, 687, 2, 56, 567];
const findMinMax = (arr = []) => {
const creds = arr.reduce((acc, val) => {
let [smallest, greatest] = acc;
if(val > greatest){
greatest = val;
};
if(val < smallest){
smallest = val;
};
return [smallest, greatest];
}, [Infinity, -Infinity]);
return creds;
};
console.log(findMinMax(arr));输出结果[2, 687]