Skip to content

Commit bab045c

Browse files
committed
20
1 parent 9cedf05 commit bab045c

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

20.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Step By Step
2+
function SecondGreatLow (arr) {
3+
// Use the sort function and pass in a callback to sort from smallest to largest
4+
// If you haven't encountered function expressions/callbacks before, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort gives a good explanation of how this method works.
5+
arr = arr.sort(function (a, b) { return a - b; });
6+
7+
// Loop through each item in the array and check if the adjacent array item is the same.
8+
for (var i = arr.length - 1; i > 0; i--) {
9+
if (arr[i] === arr[i - 1]) {
10+
// If it is, we use the .splice method to remove it.
11+
arr.splice(i, 1);
12+
}
13+
}
14+
15+
if (arr.length > 2) {
16+
// If our array is longer than two items, we return the 2nd and 2nd to last item in the array.
17+
return arr[1] + ' ' + arr[arr.length - 2];
18+
} else if (arr.length === 2) {
19+
// If our array is exactly two items long, we return the 2nd and the first item
20+
return arr[1] + ' ' + arr[0];
21+
} else {
22+
// If our array is only one item, we return the only element twice.
23+
return arr[0] + ' ' + arr[0];
24+
}
25+
}

0 commit comments

Comments
 (0)