I'm working on coderbyte challenge titled SecondGreatLow. We are given an array of numbers as a parameter and are supposed to return the second lowest # and the 2nd highest # of the given array.
I am using someone else's code - I am analyzing/reverse engineering it,but I am confused on one part. Here is the code:
function SecondGreatLow(arr) {
var unique = [arr[0]];
for(var i = 1; i < arr.length; i++) {
if (unique.indexOf(arr[i]) == -1) {
unique.push(arr[i]);
}
}
unique.sort(function(a,b){return a - b});
var smallest = unique[1].toString();
unique.reverse();
var largest = unique[1].toString();
return smallest + " " + largest;
}
I am having difficulty with the first half of the code - specifically the indexOf statement.
From reading b/w the lines and looking at the bottom half of the code, I believe that the 1st top half of the code is getting rid of all repeat values? - All of the remaining non-repeated values are popped into the unique array, where we then get the 2nd lowest (unique[1]) and the 2nd highest (unique[1] on the reversed array) values.
But what does that if-statement do???
I know that if the indexOf == -1, then that means that the particular item looked for is not found.
But if we go thru it step by step...
var unique = [arr[0]];
^ That's taking the value of the 1st element in the given array/parameter and storing it in an array named "unique"
Then there's a for-loop that starts at index 1 (rather than 0)
for(var i = 1; i < arr.length; i++) {
^So, the for loop is running through the original array that was provided as a parameter (and not thru the unique array). But this is where I get confused-
if (unique.indexOf(arr[i]) == -1) {
unique.push(arr[i]);
So let's say we're going thru the 1st iteration of the for-loop and i = 1... We want to find the index of arr[1], which would be the 2nd value of the array. BUT WHICH ARRAY? The indexOf method is being run on "unique", so are we finding the index of the 2nd value of the unique array (which currently only has (arr[0])??? Or are we finding the index of the 2nd value of the array that was passed in as a parameter?
There is no 2nd element/value in unique array on the 1st run thru the for loop (as there's only 1 value), so we'd be pushing that element / adding that element to the unique array.
Basically, I'm confused as to what the top half of the code is actually doing. Any help would be appreciated.
If you want to use an example, I guess, suppose that the array [7, 7, 12, 98, 106] is passed thru as a parameter...
Thanks in advance...