|
| 1 | +/*************************************************************************************** |
| 2 | +* * |
| 3 | +* CODERBYTE BEGINNER CHALLENGE * |
| 4 | +* * |
| 5 | +* Second Great Low * |
| 6 | +* Using the JavaScript language, have the function SecondGreatLow(arr) take the array * |
| 7 | +* of numbers stored in arr and return the second lowest and second greatest numbers, * |
| 8 | +* respectively, separated by a space. For example: if arr contains * |
| 9 | +* [7, 7, 12, 98, 106] the output should be 12 98. The array will not be empty and * |
| 10 | +* will contain at least 2 numbers. It can get tricky if there's just two numbers! * * |
| 11 | +* * |
| 12 | +* SOLUTION * |
| 13 | +* This challenge has one outlier and that is if there are only two elements in the * |
| 14 | +* array. In that case you sort the pair and return each entry as the second highest * |
| 15 | +* and second lowest. * |
| 16 | +* Outside of that I am going to sort the array in ascending order and remove * |
| 17 | +* duplicate values. Then retorn the second entry and the next to last entry. * |
| 18 | +* * |
| 19 | +* Steps for solution * |
| 20 | +* 1) Check for outlier of array with only two entries * |
| 21 | +* 2) Sort array in ascending order * |
| 22 | +* 3) Remove duplicate values * |
| 23 | +* 4) Return second and next to last values for answer * |
| 24 | +* * |
| 25 | +***************************************************************************************/ |
| 26 | + |
| 27 | +function SecondGreatLow(arr) { |
| 28 | + |
| 29 | + if (arr.length === 2) { |
| 30 | + arr.sort(function(a,b) {return a - b}); |
| 31 | + return arr[1] + " " + arr[0]; |
| 32 | + } |
| 33 | + |
| 34 | + var uniqueArray = arr.filter(function(item, pos) { |
| 35 | + return arr.indexOf(item) == pos; |
| 36 | + }); |
| 37 | + |
| 38 | + if (uniqueArray.length > 2) { |
| 39 | + uniqueArray.sort(function(a, b){return a-b}); |
| 40 | + return uniqueArray[1] + " " + uniqueArray[uniqueArray.length - 2]; |
| 41 | + } |
| 42 | + else { |
| 43 | + return uniqueArray[1] + " " + uniqueArray[0]; |
| 44 | + } |
| 45 | + |
| 46 | +} |
0 commit comments