Aly*_*une 18 javascript arrays reduce
我有一个类的代码,我应该使用reduce()方法来查找数组中的最小值和最大值.但是,我们只需要使用一次调用来减少.返回数组的大小应为2,但我知道reduce()方法总是返回一个大小为1的数组.我可以使用下面的代码获取最小值,但是我不知道如何获取同一个电话中的最大值.我假设一旦我获得了最大值,我只需在reduce()方法完成后将其推送到数组.
/**
* Takes an array of numbers and returns an array of size 2,
* where the first element is the smallest element in items,
* and the second element is the largest element in items.
*
* Must do this by using a single call to reduce.
*
* For example, minMax([4, 1, 2, 7, 6]) returns [1, 7]
*/
function minMax(items) {
var minMaxArray = items.reduce(
(accumulator, currentValue) => {
return (accumulator < currentValue ? accumulator : currentValue);
}
);
return minMaxArray;
}
Run Code Online (Sandbox Code Playgroud)
小智 19
在ES6中,您可以使用扩展运算符.一串解决方案:
Math.min(...items)
Run Code Online (Sandbox Code Playgroud)
小智 12
你可以这样使用。可以有任意数量的参数。
function minValue(...args) {
const min = args.reduce((acc, val) => {
return acc < val ? acc : val;
});
return min;
}
function maxValue(...args) {
const max= args.reduce((acc, val) => {
return acc > val ? acc : val;
});
return max;
}
Run Code Online (Sandbox Code Playgroud)
col*_*lxi 11
技巧包括提供一个空数组作为initialValue参数
arr.reduce(callback, [initialValue])
Run Code Online (Sandbox Code Playgroud)
initialValue [可选]用作第一次调用回调的第一个参数的值.如果未提供初始值,则将使用数组中的第一个元素.
所以代码看起来像这样:
function minMax(items) {
return items.reduce((acc, val) => {
acc[0] = ( acc[0] === undefined || val < acc[0] ) ? val : acc[0]
acc[1] = ( acc[1] === undefined || val > acc[1] ) ? val : acc[1]
return acc;
}, []);
}
Run Code Online (Sandbox Code Playgroud)
小智 7
您可以使用数组作为返回值:
function minMax(items) {
return items.reduce(
(accumulator, currentValue) => {
return [
Math.min(currentValue, accumulator[0]),
Math.max(currentValue, accumulator[1])
];
}, [Number.MAX_VALUE, Number.MIN_VALUE]
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25132 次 |
| 最近记录: |