You are basically dealing with a case of convenience modern JS features (spread operator) being used instead of a loop or a .reduce method. But ofc this solution could be even more small if you used Array.prototype.map
instead of the “for loop”.
If you were to not use the spread operator (…) you’d have to use the classic algorithm to determine the maximum number inside an array which involves comparing two numbers and setting up a variable that holds the maximum number by iterating every number in the sub-array like this:
const list = [5,3,10,1]
let maxNumber = Number.NEGATIVE_INFINITY
for (let number of list) {
if (number > maxNumber) {
maxNumber = number
}
}
console.log(maxNumber)
//!> 10
Or make it a bit more concise:
// version 1 with > than comparative function
console.log(
list.reduce(
(a, b) => a > b ? a : b,
Number.NEGATIVE_INFINITY
)
)
// version 2 with Math.max
// used as a binary function)
console.log(
list.reduce(
(a, b) => Math.max(a, b),
Number.NEGATIVE_INFINITY
)
)
You can even make use the fact that Math.max is a variadic-argument function (accepts multiple arguments indefinitely) that has no limits as to how many arguments you can pass to it. By invoking the Function.prototype.appy
method on Math.max you can pass a list of values and it will take them as separate arguments:
Math.max.apply(null, list) //> 10
The thing that you used “spreads” the values in the list across the argument list of Math.max instead of sending the list “as is”. So that Math.max(...[1,2,3])
becomes Math.max(1, 2, 3)
. You can also use this operator inside the parameter definition of a function if you want to accept variadic arguments.
As for the final and possibly the most concise form to solve this challenge
const largestOfFour = (arr) => arr.map(
(subList) => Math.max(...subList)
)
As to why I used the concept of -Infinity instead of the first element of the list for the maximum value before iterating, it’s just a thing I do for safety because sometimes a list may not have elements at all and the program would crash. Plus, -Infinity and Infinity are the “identities” for their respective semi-groups “maximum comparison” and “minimum comparison”.
For example:
- Which one is greater: -Infinity or 5? 5, -Infinity or -9999999999? -9999999999 of course, see the pattern? no matter which number you compare it to, that number will always be greater that the lowest possible number.
- Which one is lower: Infinity or -Infinity? -Infinity, Infinity or 567? 567… the same pattern applies but in reverse; any number pales in comparison to the monstrously big number/concept that is Infinity so it’s always gonna be the minimum of the two.