-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminMaxNumberInArray.js
More file actions
40 lines (33 loc) · 844 Bytes
/
minMaxNumberInArray.js
File metadata and controls
40 lines (33 loc) · 844 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Given an array, find it's max and min value.
* Find fastest way. Think of big arrays.
* @note: maximum size for numbers only arrays is ~120000.
*/
const numbers = [1, 10, 900, 0, 34, 66];
// Solutions, ordered from fastest to slowest
// 1. Standart loop (according to most benchmarks, for example: https://jsben.ch/dZHfx)
let max = numbers[0];
for (let i = 1; i < numbers.length; ++i) {
if (numbers[i] > max) {
max = numbers[i];
}
}
let min = numbers[0];
for (let i = 1; i < numbers.length; ++i) {
if (numbers[i] < min) {
min = numbers[i];
}
}
// 2. Apply
Math.min.apply(null, numbers);
Math.max.apply(null, numbers);
// 3. ES6
Math.min(...numbers);
Math.max(...numbers);
// 4. Reduce
numbers.reduce(function(a, b) {
return Math.max(a, b);
});
numbers.reduce(function(a, b) {
return Math.min(a, b);
});