-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
two-oldest-ages-1.js
87 lines (76 loc) · 1.66 KB
/
two-oldest-ages-1.js
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
function twoOldestAges(ages) {
// sort the array lowest to highest
ages.sort((a, b) => {
if (a < b) {
return -1;
}
if (b < a) {
return 1;
}
return 0;
});
// return the last 2 values in the array
const result = [];
result.push(ages[ages.length - 2]);
result.push(ages[ages.length - 1]);
return result;
}
function twoOldestAges(ages) {
// sort the array lowest to highest
ages.sort((a, b) => a - b);
// return the last 2 values in the array
return ages.slice(ages.length - 2);
}
function twoOldestAges(ages) {
return ages
.sort((a, b) => a - b)
.slice(ages.length - 2);
}
function twoOldestAges(ages) {
return ages
.sort((a, b) => a - b)
.slice(-2);
}
// pure
function twoOldestAges(ages) {
return ages
.slice()
.sort((a, b) => a - b)
.slice(-2);
}
// pure
function twoOldestAges(ages) {
return [...ages]
.sort((a, b) => a - b)
.slice(-2);
}
// Alca!
const result = (ages => {
const oldest = Math.max(...ages);
const set = new Set(ages);
set.delete(oldest);
return [ Math.max(...set), oldest ]; }
)([ 1, 2, 10, 8 ])
console.log(result);
function twoOldestAges(ages) {
let secondLargest = ages[0];
let largest = ages[1];
if (secondLargest > largest) {
[secondLargest, largest] = [largest, secondLargest];
}
for (let i = 2; i < ages.length; i++) {
const value = ages[i];
if (value > secondLargest) {
secondLargest = value;
if (secondLargest > largest) {
[secondLargest, largest] = [largest, secondLargest];
}
}
}
return [secondLargest, largest];
}
const input = [2, 1, 10, 8];
console.log(
twoOldestAges(input),
[8, 10]
);