The Where do I belong challenge was relatively straightforward. However, it was a surprise how easily the callbackFunction worked.
The goal of this challenge: Return the lowest index at which a value (second argument) should be inserted into a sorted array (first argument).
The suggested method is Array.sort().
Best Solution
function where(arr, num) { arr.push(num); // add num to array arr.sort(function (a,b) { return a - b; }); // perform sort from lowest to highest return arr.indexOf(num); // return index of num } where([40, 60], 50);
And here’s a CodePen with my solution in action: http://codepen.io/allurewebsolutions/pen/JYNOom
Code Breakdown
From Mozilla: The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points – in English that means alphabetical.
The first thing we do is add num to the arr array. Then we need to sort the resulting array from lowest integer to highest. We do that using a callbackFunction within the sort() method. The sort() method sorts alphabetically by default, which is why we need the callbackFunction.
Our callbackFunction works, by taking two values at a time within arr, then subtracting them and seeing if the resulting value is less or greater than zero. Then it iterates throughout all the numbers in the array, comparing each of them against each other.
To get an in-depth explanation of the integer sort function, Stack Overflow has a good thread on it.
Finally, once all of the numbers are sorted, we return the index of num.
Alternative Solution
function where(arr, num) { arr.push(num); arr.sort(function (a,b) { return a - b; }); // perform sort from lowest to highest for(i = 0; i < arr.length; i++) { if(arr[i] === num) { return i; } } } where([40, 60], 50);
In this alternative code, we aren’t returning the index of num. Instead we are running a for loop that takes each element in arr and compares it against num. Then the i (# of iteration in the loop) is returned, which is equivalent to the position of num inside the array. indexOf() is so much easier 🙂
Discussion
I would love to hear others’ solutions and discover better and cooler ways to solve these challenges. Please comment with your questions, suggestions, or anything you would like.
If you found my solution useful or learned something new from this blog post, please feel free add kudos inside the main chat of Free Code Camp: Thanks @allurewebsolutions