No.107 question in BFE.dev, link here Find the largest difference.
largestDiff([-1, 2,3,10, 9])
// 11, obviously Math.abs(-1 - 10) is the largest
largestDiff([])
// 0
largestDiff([1])
// 0
In this question, we are asked to get the largest difference among a pair of numbers. For example, in the first case which the question provided, the largest diffenence among these numbers are minus 1 and 10, so the absolute value of them is 11.
So to implement the function, we can use Math’s apis, of course we need to check edge case first, when arr.length equals to 0 or 1 return 0, just like the examples this question provided. Then, just return Math.abs(Math.max(…arr) - Math.min(…arr)), so Math.max to find the maximum value in arr, and Math.min finding the minimum one in arr.
function largestDiff(arr) {
if (arr.length === 0 || arr.length === 1) return 0
return Math.abs(Math.max(...arr) - Math.min(...arr))
}
But we can also use another way to solve it, without using Math’s apis, we can use for loop to find maximum value and minimum value in arr, and return max value minus minimum value
function largestDiff(arr) {
if (arr.length === 0 || arr.length === 1) return 0
let min = Infinity
let max = -Infinity
for (let item of arr) {
if (item < min) {
min = item
} else if (item > max) {
max = item
}
}
return max - min
}
本文介绍了如何在JavaScript中使用Math库函数和for循环来找到数组中两数的最大差值,讨论了处理边缘情况的方法,并提供了两种不同的实现方式:一种利用Math.max和Math.min,另一种使用循环找出最大值和最小值。

被折叠的 条评论
为什么被折叠?



