我怎样才能轻松地获得一个JavaScript数组的最小或最大元素?
伪代码示例:
let array = [100, 0, 50]
array.min() //=> 0
array.max() //=> 100
我怎样才能轻松地获得一个JavaScript数组的最小或最大元素?
伪代码示例:
let array = [100, 0, 50]
array.min() //=> 0
array.max() //=> 100
当前回答
下面的脚本在ndoejs中为我工作:
var numbers = [1, 2, 3, 4];
console.log('Value:: ' + Math.max.apply(null, numbers) ); // 4
其他回答
这里有很多不错的答案,下面是一个typescript版本,可以处理一些值未定义的列表。
如何使用:
const testDates = [
undefined,
new Date('July 30, 1986'),
new Date('July 31, 1986'),
new Date('August 1, 1986'),
]
const max: Date|undefined = arrayMax(testDates); // Fri Aug 01 1986
const min: Date|undefined = arrayMin(testDates); // Min: Wed Jul 30 1986
const test: Date = arrayMin(testDates); // Static type error
const anotherTest: undefined = arrayMin(testDates); // Static type error
定义(notEmpty定义来自这篇文章):
function arrayMax<T>(values?: (T | null | undefined)[]): T | undefined {
const nonEmptyValues = filterEmpty(values);
if (nonEmptyValues.length === 0) {
return undefined;
}
return nonEmptyValues.reduce((a, b) => (a >= b ? a : b), nonEmptyValues[0]);
}
function arrayMin<T>(values?: (T | null | undefined)[]): T | undefined {
const nonEmptyValues = filterEmpty(values);
if (nonEmptyValues.length === 0) {
return undefined;
}
return nonEmptyValues.reduce((a, b) => (a <= b ? a : b), nonEmptyValues[0]);
}
function filterEmpty<T>(values?: (T | null | undefined)[] | null): T[] {
return values?.filter(notEmpty) ?? [];
}
function notEmpty<T>(value: T | null | undefined): value is T {
if (value === null || value === undefined) return false;
const testDummy: T = value;
return true;
}
我没有使用数学。max函数,正如文档中建议的那样,因为这样我就可以将这个函数与任何可比对象一起使用(如果你知道如何键入它,请告诉我,这样我就可以更好地定义T)。
很简单,真的。
var arr = [10,20,30,40];
arr.max = function() { return Math.max.apply(Math, this); }; //attach max funct
arr.min = function() { return Math.min.apply(Math, this); }; //attach min funct
alert("min: " + arr.min() + " max: " + arr.max());
下面的脚本在ndoejs中为我工作:
var numbers = [1, 2, 3, 4];
console.log('Value:: ' + Math.max.apply(null, numbers) ); // 4
为了防止“max”和“min”被列在“for…”在“循环:
Object.defineProperty(Array.prototype, "max", {
enumerable: false,
configurable: false,
writable: false,
value: function() {
return Math.max.apply(null, this);
}
});
Object.defineProperty(Array.prototype, "min", {
enumerable: false,
configurable: false,
writable: false,
value: function() {
return Math.min.apply(null, this);
}
});
用法:
var x = [10,23,44,21,5];
x.max(); //44
x.min(); //5
对于一个简洁的现代解决方案,可以对数组执行reduce操作,跟踪当前的最小值和最大值,因此数组只迭代一次(这是最优的)。为了简洁起见,这里使用了解构赋值。
Let array = [100, 0, 50]; Let [min, max] =数组。减少(((prevMin prevMax],咕咕叫)= > (数学。min(prevMin, curr),数学。max(prevMax, curr)],[∞,-∞]); console.log(“分钟:分钟); console.log(“马克斯:Max);
为了只找到最小值或最大值,我们可以以大致相同的方式使用执行reduce操作,但我们只需要跟踪之前的最优值。这种方法比使用apply更好,因为当数组对堆栈来说太大时,它不会导致错误。
Const arr = [- 1,9,3, - 6,35]; //只找到最小值 const min = arr.reduce((a,b)=>Math.min(a,b),无穷大); console.log(“分钟:Min); / / 6 //只找到最大值 const max = arr.reduce((a,b)=>Math.max(a,b), -无穷大); console.log(“马克斯:Max); / / 35