使用 reduce() 查找最小值和最大值?
Using reduce() to find min and max values?
我有一个 class 的代码,我应该在其中使用 reduce()
方法来查找数组中的最小值和最大值。但是,我们只需要使用一次 reduce 调用。 return 数组的大小应为 2,但我知道 reduce()
方法总是 return 大小为 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;
}
使用Math.min()
和Math.max()
函数的解决方案:
function minMax(items) {
var minMaxArray = items.reduce(function (r, n) {
r[0] = (!r[0])? n : Math.min(r[0], n);
r[1] = (!r[1])? n : Math.max(r[1], n);
return r;
}, []);
return minMaxArray;
}
console.log(minMax([4, 1, 2, 7, 6]));
技巧在于提供一个空数组作为初始值参数
arr.reduce(callback, [initialValue])
initialValue [Optional] Value to use as the first argument to the
first call of the callback. If no initial value is supplied, the first
element in the array will be used.
所以代码看起来像这样:
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;
}, []);
}
您可以使用数组作为 return 值:
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]
);
}
由于根本不需要 reduce 调用,您可以从中获得一些乐趣
let items = [62, 3, 7, 9, 33, 6, 322, 67, 853];
let arr = items.reduce((w,o,r,k,s=Math)=>[s.min.apply(0, k),s.max.apply(0, k)],[]);
console.log(arr);
您真正需要的是 let minMaxArray = [Math.min.apply(0,items), Math.max.apply(0,items)]
在 ES6 中你可以使用扩展运算符。一串解法:
Math.min(...items)
我知道这已经得到回答,但我离开了 (这似乎不完整)并且能够在 2 行中获得最小值和最大值:
let vals = [ numeric values ]
let min = Math.min.apply(undefined, vals)
let max = Math.max.apply(undefined, vals)
我确实看到了 Array.reduce
中的价值,但是对于这样一个超级简单的用例, 和 只要您了解 Function.apply
的作用,这将是我的 goto 解决方案。
1。仅使用 Math.min
和 Math.max
的解决方案:
⚠️
如果你使用大数组,这将不起作用,即提供 Math.min()
与许多参数作为 " 你 运行 超过 JavaScript 引擎参数的风险长度限制。应用带有太多参数(想想超过数万个参数)的函数的后果因引擎而异(JavaScript核心硬编码参数限制为 65536),因为限制(实际上甚至是任何过大堆栈行为的性质)是未指定的。一些引擎会抛出异常。“ from MDN web docs.
function minMax(items) {
return [
Math.min.apply(null, items),
Math.max.apply(null, items)
]
}
... 或者如果您更喜欢 ES6's Spread syntax:
const minMax = items => [
Math.min(...items),
Math.max(...items)
]
2。使用 Array.prototype.reduce
、Math.min
和 Math.max
的解决方案
function minMax(arr) {
return arr.reduce(function(acc, cur) {
return [
Math.min(cur, acc[0]),
Math.max(cur, acc[1])
]
}, [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]);
}
...或缩短:
const minMax = items =>
items.reduce((acc, cur) =>
[Math.min(cur, acc[0]), Math.max(cur, acc[1])],
[Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]
)
3。包括合理验证的解决方案
function minMax(items) {
let newItems = []
const isArray = Array.isArray(items)
const onlyHasNumbers = !items.some(i => isNaN(parseFloat(i)))
// only proceed if items is a non-empty array of numbers
if (isArray && items.length > 0 && onlyHasNumbers) {
newItems = items.reduce((acc, cur) => [
Math.min(cur, acc[0]),
Math.max(cur, acc[1])
], [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY])
}
return newItems
}
Documentation for Math.min
Documentation for Math.max
Documentation for Array.prototype.reduce()
使用 reduce 函数获取数组的最小值和最大值
const ArrayList = [1, 2, 3, 4, 3, 20, 0];
const LargestNum = ArrayList.reduce((prev, curr) => {
return Math.max(prev, curr)
});
const MinNum = ArrayList.reduce((prev,curr)=>{
return Math.min(prev,curr)
});
console.log(LargestNum);
console.log(MinNum);
const values = [1,2,3,4,5];
const [first] = values;
const maxValue = values.reduce((acc, value) => Math.max(acc, value), first);
let arr = [8978, 'lol', -78, 989, NaN, null, undefined, 6, 9, 55, 989];
let minMax = arr.reduce(([min, max], v) => [
Math.min(min, v) || min,
Math.max(max, v) || max], [Infinity, -Infinity]);
console.log(minMax);
工作原理:
|| min
检查是v
号。
[Infinity, -Infinity]
是.reduce
初始值
使用js destructuring赋值
你可以这样使用。可以有任意数量的参数。
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;
}
我们可以通过声明一个空数组作为 reduce 函数的累加器值,然后在 reduce 方法的最后一次迭代中执行一组不同的操作来实现这一点。我们通过将所有四个参数传递给 reduce 方法(总计、项目、索引、数组)并使用索引与数组长度的比较来在最后一次迭代中做一些不同的事情来做到这一点。
var prices = [32.99, 21.99, 6.99, 4.99, 12.99, 8.98, 5.99];
var highLowPrices = prices.reduce(function(accumulatorArray, price, index, pricesArray){
if (index === pricesArray.length-1){
accumulatorArray.push(price);
var returnArray = [];
accumulatorArray.sort(function(price1, price2){
return price1 - price2;
});
var lowestPrice = accumulatorArray[0];
var highestPrice = accumulatorArray[accumulatorArray.length-1];
returnArray.push(lowestPrice);
returnArray.push(highestPrice);
return returnArray;
} else {
accumulatorArray.push(price);
return accumulatorArray;
}
}, []);
console.log(highLowPrices);
我故意使用了一些不必要的步骤,并使用了语义冗长的变量名称以使逻辑更清晰。
if (index === pricesArray.length-1)
表示在 reduce 方法通过价格数组的最后一次迭代中,发生了一组不同的操作。到那时,我们只是重新创建价格数组,这是微不足道的。但是在最后一次迭代中,在完全重新创建价格数组之后,我们做了一些不同的事情。我们创建另一个空数组,我们打算 return。然后我们对 'accumulatorArray' 变量进行排序——这是重新创建的价格数组,从低到高排序。我们现在采用最低价和最高价并将它们存储在变量中。按升序对数组进行排序后,我们知道最低的在索引 0 处,最高的在索引 array.length - 1 处。然后我们将这些变量放入我们之前声明的 return 数组中。而不是 return 累加器变量本身,我们 return 我们自己特别声明的 return 数组。结果是一个数组,先是最低价,然后是最高价。
这是一个 reduce 与 Array 的例子
const result = Array(-10,1,2,3,4,5,6,7,8,9).reduce((a,b)=>{ return (a<b) ? a : b })
您可能想使用相同的方法来获取字符串的长度
const result = Array("ere","reeae","j","Mukono Municipality","Sexy in the City and also").reduce((a,b)=>{ return (a.length<b.length) ? a : b })
我有一个 class 的代码,我应该在其中使用 reduce()
方法来查找数组中的最小值和最大值。但是,我们只需要使用一次 reduce 调用。 return 数组的大小应为 2,但我知道 reduce()
方法总是 return 大小为 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;
}
使用Math.min()
和Math.max()
函数的解决方案:
function minMax(items) {
var minMaxArray = items.reduce(function (r, n) {
r[0] = (!r[0])? n : Math.min(r[0], n);
r[1] = (!r[1])? n : Math.max(r[1], n);
return r;
}, []);
return minMaxArray;
}
console.log(minMax([4, 1, 2, 7, 6]));
技巧在于提供一个空数组作为初始值参数
arr.reduce(callback, [initialValue])
initialValue [Optional] Value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used.
所以代码看起来像这样:
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;
}, []);
}
您可以使用数组作为 return 值:
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]
);
}
由于根本不需要 reduce 调用,您可以从中获得一些乐趣
let items = [62, 3, 7, 9, 33, 6, 322, 67, 853];
let arr = items.reduce((w,o,r,k,s=Math)=>[s.min.apply(0, k),s.max.apply(0, k)],[]);
console.log(arr);
您真正需要的是 let minMaxArray = [Math.min.apply(0,items), Math.max.apply(0,items)]
在 ES6 中你可以使用扩展运算符。一串解法:
Math.min(...items)
我知道这已经得到回答,但我离开了
let vals = [ numeric values ]
let min = Math.min.apply(undefined, vals)
let max = Math.max.apply(undefined, vals)
我确实看到了 Array.reduce
中的价值,但是对于这样一个超级简单的用例, 和 只要您了解 Function.apply
的作用,这将是我的 goto 解决方案。
1。仅使用 Math.min
和 Math.max
的解决方案:
⚠️
如果你使用大数组,这将不起作用,即提供 Math.min()
与许多参数作为 " 你 运行 超过 JavaScript 引擎参数的风险长度限制。应用带有太多参数(想想超过数万个参数)的函数的后果因引擎而异(JavaScript核心硬编码参数限制为 65536),因为限制(实际上甚至是任何过大堆栈行为的性质)是未指定的。一些引擎会抛出异常。“ from MDN web docs.
function minMax(items) {
return [
Math.min.apply(null, items),
Math.max.apply(null, items)
]
}
... 或者如果您更喜欢 ES6's Spread syntax:
const minMax = items => [
Math.min(...items),
Math.max(...items)
]
2。使用 Array.prototype.reduce
、Math.min
和 Math.max
的解决方案
function minMax(arr) {
return arr.reduce(function(acc, cur) {
return [
Math.min(cur, acc[0]),
Math.max(cur, acc[1])
]
}, [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]);
}
...或缩短:
const minMax = items =>
items.reduce((acc, cur) =>
[Math.min(cur, acc[0]), Math.max(cur, acc[1])],
[Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]
)
3。包括合理验证的解决方案
function minMax(items) {
let newItems = []
const isArray = Array.isArray(items)
const onlyHasNumbers = !items.some(i => isNaN(parseFloat(i)))
// only proceed if items is a non-empty array of numbers
if (isArray && items.length > 0 && onlyHasNumbers) {
newItems = items.reduce((acc, cur) => [
Math.min(cur, acc[0]),
Math.max(cur, acc[1])
], [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY])
}
return newItems
}
Documentation for Math.min
Documentation for Math.max
Documentation for Array.prototype.reduce()
使用 reduce 函数获取数组的最小值和最大值
const ArrayList = [1, 2, 3, 4, 3, 20, 0];
const LargestNum = ArrayList.reduce((prev, curr) => {
return Math.max(prev, curr)
});
const MinNum = ArrayList.reduce((prev,curr)=>{
return Math.min(prev,curr)
});
console.log(LargestNum);
console.log(MinNum);
const values = [1,2,3,4,5];
const [first] = values;
const maxValue = values.reduce((acc, value) => Math.max(acc, value), first);
let arr = [8978, 'lol', -78, 989, NaN, null, undefined, 6, 9, 55, 989];
let minMax = arr.reduce(([min, max], v) => [
Math.min(min, v) || min,
Math.max(max, v) || max], [Infinity, -Infinity]);
console.log(minMax);
工作原理:
|| min
检查是v
号。[Infinity, -Infinity]
是.reduce
初始值使用js destructuring赋值
你可以这样使用。可以有任意数量的参数。
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;
}
我们可以通过声明一个空数组作为 reduce 函数的累加器值,然后在 reduce 方法的最后一次迭代中执行一组不同的操作来实现这一点。我们通过将所有四个参数传递给 reduce 方法(总计、项目、索引、数组)并使用索引与数组长度的比较来在最后一次迭代中做一些不同的事情来做到这一点。
var prices = [32.99, 21.99, 6.99, 4.99, 12.99, 8.98, 5.99];
var highLowPrices = prices.reduce(function(accumulatorArray, price, index, pricesArray){
if (index === pricesArray.length-1){
accumulatorArray.push(price);
var returnArray = [];
accumulatorArray.sort(function(price1, price2){
return price1 - price2;
});
var lowestPrice = accumulatorArray[0];
var highestPrice = accumulatorArray[accumulatorArray.length-1];
returnArray.push(lowestPrice);
returnArray.push(highestPrice);
return returnArray;
} else {
accumulatorArray.push(price);
return accumulatorArray;
}
}, []);
console.log(highLowPrices);
我故意使用了一些不必要的步骤,并使用了语义冗长的变量名称以使逻辑更清晰。
if (index === pricesArray.length-1)
表示在 reduce 方法通过价格数组的最后一次迭代中,发生了一组不同的操作。到那时,我们只是重新创建价格数组,这是微不足道的。但是在最后一次迭代中,在完全重新创建价格数组之后,我们做了一些不同的事情。我们创建另一个空数组,我们打算 return。然后我们对 'accumulatorArray' 变量进行排序——这是重新创建的价格数组,从低到高排序。我们现在采用最低价和最高价并将它们存储在变量中。按升序对数组进行排序后,我们知道最低的在索引 0 处,最高的在索引 array.length - 1 处。然后我们将这些变量放入我们之前声明的 return 数组中。而不是 return 累加器变量本身,我们 return 我们自己特别声明的 return 数组。结果是一个数组,先是最低价,然后是最高价。
这是一个 reduce 与 Array 的例子
const result = Array(-10,1,2,3,4,5,6,7,8,9).reduce((a,b)=>{ return (a<b) ? a : b })
您可能想使用相同的方法来获取字符串的长度
const result = Array("ere","reeae","j","Mukono Municipality","Sexy in the City and also").reduce((a,b)=>{ return (a.length<b.length) ? a : b })