JavaScript tips — Find the maximum value in an array of numbers

preview_player
Показать описание
You can find the largest number in an array in #JavaScript with a single function call and without writing any loops

To find the max value in a very large array, instead use reduce:

This will work even for arrays with millions of elements
Рекомендации по теме
Комментарии
Автор

Why does spread fail when the array is large? The max function receives the arguments as an array.

Steve-Richter
Автор

i like to explore several approaches for hypothetical situations like this.
Reduce should work pretty fast. i guess it'll hardly take a couple milliseconds.

solution 2: - but probably slow as hell - would be sorting the array and returning the last element of it. Something like:
- 1]

solution 3: coming to my mind is offloading a for ... of ... loop into a function.
let biggest = null;
for (const x of bigArray) {
if (x > biggest) biggest = x;
}

solution 4: the good old for loop with an index.
let biggest = null;
for (let i = 0; i < bigArray.length; i++) {
if (bigArray[i] > biggest) biggest = bigArray[i];
}

---

Before posting the comment i took a minute and tested mentioned approaches for performance (out of curiosity)
solution 1: The ReduceFN takes about 15-18ms on my Machine
solution 2: The Sort() approach a whopping 2-3 Seconds (which is expected when sorting a million elements)
solution 3: The for .. of.. loop surprised me. it took 27-30ms - i expected it to be faster than the reduce function as we spare a Math.max function call and have a native loop.
solution 4: the good old for loop with index. 6-9 ms. yep. thats probably offloaded into some C++ magic in the Engine.

But thats a super interesting insight. in some cases you get a x5 performance boost by just switching from a convenient for..of loop to an index based for loop.
i guess reduce also beats the for..of loop because they utilize an index based loop internally?


That was a fun little exercise, thanks for the video :)

Chrrs