js find the maximum and minimum values in an array All In One
js find the maximum and minimum values in an array All In One
js 找出数组中的最大值与最小值 All In One
number / number string
build in methods
Math.max
&Math.min
const arr = [9, 1, 3, 7, 12, 37, 23];
const max = Math.max(...arr);
const min = Math.min(...arr);
console.log(`max =`, max);
console.log(`min =`, min);
// max = 37
// min = 1
const arr = ['9', '1', '3', '7', '12', '37', '23'];
const max = Math.max(...arr);
const min = Math.min(...arr);
// OR
const max = Math.max(...arr.map(Number));
const min = Math.min(...arr.map(Number));
console.log(`max =`, max);
console.log(`min =`, min);
// max = 37
// min = 1
sort
const arr = [9, 1, 3, 7, 12, 37, 23];
// arr.sort();
// [1, 12, 23, 3, 37, 7, 9] ❌
// arr.sort((a, b) => a - b > 0 ? 1 : -1);
// [1, 3, 7, 9, 12, 23, 37] ✅
arr.sort((a, b) => a - b);
// [1, 3, 7, 9, 12, 23, 37] ✅
const max = arr[arr.length - 1];
const min = arr[0];
console.log(`max =`, max);
console.log(`min =`, min);
// max = 37
// min = 1
string
not work for string ❌
const arr = ['c', 'b', 'a', 'c1', 'b2', 'a3', 'abc'];
const max = Math.max(...arr);
const min = Math.min(...arr);
console.log(`max =`, max);
console.log(`min =`, min);
// max = NaN
// min = NaN
custom sort function ✅
const arr = ['c', 'b', 'a', 'c1', 'b2', 'a3', 'abc'];
// dict
'c'.charCodeAt(0);
// 99
'cba'.charCodeAt(2);
// 97
'cba'.charAt();
// 'c'
'cba'.charAt(2);
// 'a'
String.fromCharCode(97, 98, 99);
// 'abc'
refs
numbers ✅
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min
strings / chars
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/16737535.html
未经授权禁止转载,违者必究!