我怎样才能轻松地获得一个JavaScript数组的最小或最大元素?
伪代码示例:
let array = [100, 0, 50]
array.min() //=> 0
array.max() //=> 100
我怎样才能轻松地获得一个JavaScript数组的最小或最大元素?
伪代码示例:
let array = [100, 0, 50]
array.min() //=> 0
array.max() //=> 100
当前回答
var max_of_array = Math.max.apply(Math, array);
完整的讨论见: http://aaroncrane.co.uk/2008/11/javascript_max_api/
其他回答
对于包含对象而不是数字的数组:
arr = [
{ name: 'a', value: 5 },
{ name: 'b', value: 3 },
{ name: 'c', value: 4 }
]
你可以使用reduce来获取最小值(min)的元素
arr.reduce((a, b) => a.value < b.value ? a : b)
// { name: 'b', value: 3 }
或最大值(max)
arr.reduce((a, b) => a.value > b.value ? a : b)
// { name: 'a', value: 5 }
这里有很多不错的答案,下面是一个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)。
出于学习目的,你可以使用变量和For循环,而不使用内置函数。
// Input sample data to the function var arr = [-1, 0, 3, 100, 99, 2, 99]; // Just to show the result console.log(findMinMax(arr)); function findMinMax(arr) { let arraySize = arr.length; if (arraySize > 0) { var MaxNumber = MinNumber = arr[0]; for (var i = 0; i <= arraySize; i++) { if (arr[i] > MaxNumber) { MaxNumber = arr[i]; }else if(arr[i] < MinNumber) { MinNumber = arr[i]; } } var minMax = [MinNumber,MaxNumber]; return minMax; } else { return 0; } }
你可以通过扩展Array类型来实现:
Array.max = function( array ){
return Math.max.apply( Math, array );
};
Array.min = function( array ){
return Math.min.apply( Math, array );
};
从这里开始(作者:John Resig)
除了使用数学函数max和min之外,另一个要使用的函数是sort()的内置函数:开始吧
const nums = [12, 67, 58, 30].sort((x, y) =>
x - y)
let min_val = nums[0]
let max_val = nums[nums.length -1]