Bonfire: Where Do I Belong Solution

I was getting excited months ago when Where Do I Belong was the last of the foreseeable Beginner’s Bonfires we’d be doing. But it looks like there’s one more after this so let’s see what Free Code Camp has for us this time:

function where(arr, num) {
  // Find my place in this sorted array.
  return num;
}

where([40, 60], 50);

Looks like our Bonfire wants us to locate and return the lowest number where num should be placed. So, for example, if we had an array like [3, 5, 8, 12, 17] and we wanted this Bonfire to run and spit out where the number 10 would belong, it would return 2 because 8 is the lowest number that is less than 10 and it is in the second position in our array. The Bonfire gives us a clue about using sort(). Let’s start there.

Approaching the Problem

  • Sort is actually one of the first things we need to do to the array so we can organize the numbers in the off-chance the Bonfire gives us a list of numbers that isn’t chronological. So sort() is called pretty much immediately upon entering the function.
  • We’re going to need to determine which number is larger than num and for that, we’ll have to loop through our array to find that number.
  • Once we know what the number is, we’ll have to return its place in the array as the answer.

Sorting Through Sort()

Sort() is a method used on arrays to arrange the values in order. The order imposed by sort() is a bit hairy so you’ll have to be careful when using it. Sort() can take in a function that you may wish to write in order to specify the sorting and comparison process. If you don’t supply sort() with a function, it will do its best. Very often, though, this involves sort() converting your number values (if any) into strings.

In terms of sorting order, here’s what sort() interprets when you don’t feed a compare function into it…

  1. Numbers
  2. Uppercase Characters
  3. Lowercase Characters

So, let’s put this into action. Here’s an array sorted using sort():

var myArray = ["4 Badgers", "five goats", 3, 19, "Elephant"];
console.log(myArray.sort());

Here’s the output: [ 19, 3, “4 Badgers”, “Elephant”, “five goats” ]

You’re going to find something pretty obviously wrong with the outputted array. Why is 19 supposedly greater than 3? Because sort() is looking only at the first character in the string. So it’s really only seeing this: 1, 2, 4, E, f. What you’ll need to do in order to get your numbers to sort accurately is include a compare function like this:

var myArray = [41, 892, 6, 29, 7, 88];
myArray.sort( function(a,b) {
return a - b;
});
console.log(myArray);

And the output: [ 6, 7, 29, 41, 88, 892 ]

Fantastic, our numbers are being sorted accurately now. Interesting thing to note is if you want descending instead of ascending order, here’s how you’d get sort to work that out:

var myArray = [90, 4, 12, 998, 57, 16];
myArray.sort( function(a,b) {
return b - a;
});
console.log(myArray);

And you should get: [ 998, 90, 57, 16, 12, 4 ]

Pretty nifty! Though if you tried to run that through with the array earlier where we mixed and matched numbers and strings, the order of the strings are still messed up. In order to get a fully accurate sort, we would have to work with regex and that would veer off into a direction that is far beyond what this Bonfire is asking us to do. So, let’s get back to the Where Do I Belong Bonfire now that we understand how sort() is working.

Sorting Out Where Do I Belong

Here’s what I’m working with first. We know that we need to sort an array with numbers inside of it and just to keep things simple, I’m going to sort the array in ascending order (going from smallest to largest). Here’s what I’m getting:

function where(arr, num) {
arr.sort( function(a, b) {
 return a - b;
 });
return num;
 }

where([40, 60], 50);

Nothing fancy going on yet that we haven’t already encountered and we’re putting sort to good use. We can now assume that whatever numbers are in our array will now be sorted in ascending order. Our next order of business is to loop through that array and compare the numbers to num to locate the one in line that’s less than or equal to num. There’s a bit of a catch here because whatever we get, we’re going to have to convert it into an int to return a valid answer for our Bonfire. This is where parseInt() comes into play. It’s detour time.

A Little Detour into parseInt()

parseInt() is a method, often used when working with sort() because the latter will tend to convert your numbers into strings so it can work with them better. All things about passing Bonfires aside, putting out a string that’s a number is much sloppier than just putting out a straight up number. Especially given our task at hand here where we should clearly be putting a number through the validation and not a string. So that’s where parseInt() comes into play with our Where Do I Belong Bonfire.

parseInt() takes in strings and returns an integer (or number). It takes in two parameters, a string and a radix. If you ask me what a radix is, you will get to see a fantastic deer in the headlights look. If I were to explain it as simply as I can, a radix is a base numbering system or how many numbers are in an ordering system. Probably the most recognizable radix out there is the base 10 system. Which we should all be familiar with because it looks like this:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Another numbering system you might be familiar with is Base 16, which is also known as hexadecimal. So, before this throbbing headache of mine gets worse, let’s put parseInt() into action so we can see how it works:

console.log(parseInt("19, 897, 56", 10));

And the output: 19

console.log(parseInt("math scares me", 10));

The output: NaN

parseInt(), in a really simplified nutshell is returning the first character it encounters. So if it’s not a number, it returns as a NaN. If it is a number, it determines the radix you want and returns the number accordingly. Interestingly enough, your second parameter (or your radix) can be a number from 2 to 36. Now that we’ve had this brief visit into the terrifying workings of parseInt(), let’s get back to our Bonfire.

The Where Do I Belong Solution

With that having been said, here’s our solution…

function where(arr, num) {
arr.sort( function(a, b) {
 return a - b;
 });
for (var i = 0; i <= arr.length; i++) {
 if (arr[i] >= num) return parseInt(i);
 }
 return arr.length;
 }

where([40, 60], 50);

After sorting our array, I created a for loop that checks all the values inside of the arr array. As it loops through each value it checks to see if that particular value is greater than or equal to num. If it is, the loop exits and returns the position of that number in the form of an integer, which is where parseInt() comes into play. Plug it into the Bonfire and you’ll get a pass.

Resources

Javascript Kit, Sorting a Javascript Array
Great explanation with really easy to understand examples of sort().

MDN, parseInt()
MDN’s page on parseInt(), a method that my fingers keep trying to type as praseInt().

StackOverflow, How Do I Convert a String Into an Integer
A super helpful question and answer and briefly covers the use of parseInt().


Posted

in

by

Comments

12 responses to “Bonfire: Where Do I Belong Solution”

  1. steven

    Hi, I love your examples every time I complete one I come here and see how you did it and your explanations are the best, below is my answer which is a bit different.

    arr.push(num); //insert number at the end of array
    arr.sort(function(a, b)
    {
    return a-b;
    }); //sort numbers in order
    var position = arr.indexOf(num); //find position of number inserted
    return position;

    1. Thanks, steven! I’m glad these have been helpful to you. Your solution looks pretty solid, great job! 😀

  2. Really felt good about this one. Strangely I started off thinking I’ll never understand this stuff. Then I considered your game plan and I was able to write the sort code without looking at your solution. I got that off the MDN page so I actually do read that stuff.

    I was able to figure out the basic structure of the for loop and with a few hints from your solution I was home free.

    Thanks,

    1. Great work, Mark. I’m really happy you’ve been finding these Bonfires helpful. 😀

  3. Kristina

    My solution was to add that num to the string and return the position where the num is supposed to be. Here’s my solution:

    function getIndexToIns(arr, num) {
    // Find my place in this sorted array.
    //Yay! Did it without looking up solutions!!!
    var secondArray = [];
    secondArray.push(num);
    var newArray = arr.concat(secondArray);

    newArray.sort(function(a, b) {
    return a-b;
    });

    var location = newArray.indexOf(num);
    return location;
    }

    getIndexToIns([40, 60], 50);

    1. Thanks so much for posting your solution, Kristina. It’s great to see the different approaches to these Bonfires. 😀

  4. Intosh

    Not sure why parseInt(i) since i is a var going from 0 to arr.length and is being incremented with i++. It will always remain an integer.

    1. Hi Intosh, the way I looked at it, parseInt() is used as an assurance that whatever we spit out from the loop is, indeed, an integer. You are right though, it’s not strictly necessary as you see in the test case above or for validation on FCC. Trimming it might save on some efficiency while still allowing the code to run and validate:

      function where(arr, num) {
      arr.sort( function(a, b) {
      return a – b;
      });
      for (var i = 0; i <= arr.length; i++) { if (arr[i] >= num) return i;
      }
      return arr.length;
      }

      where([40, 60], 50);

      Good catch!

  5. Adam

    So, my work matched yours (with the exception of parseInt() which I’d never heard of before) until your final return statement. Why does arr.length work? I would have thought that would just return the length of the entire Array.

    By the way, I just want to echo what so many others have already said in your comments to this point. These entries are amazing and so much more detailed than the Mozilla blog…as well as a lot more interesting to read. I don’t feel as though my brain is draining out through my ears like I do when I’m sorting through all of that info.

    1. Hi Adam, no problem. arr.length is used to ensure that we run through all the values in the array to account for each of them no matter how many there happen to be.

  6. Chris

    Firstly, you blog has been so helpful to me as a new programmer. Also, I love how people can work through the same problem, and have completely different solutions. For example, I’ll paste mine below… your’s is quite a bit more eloquent. ha.

    var sorted = arr.sort(function(a,b){
    return a – b;
    });
    if (num arr.length) {
    arr.push(num);
    }
    var i = 0;
    while (num >= sorted[i]) {
    if (num <= sorted[i + 1]) {
    return i + 1;
    }
    i++;
    }
    }

    1. Thanks for dropping by and leaving a comment, Chris. I think your solution is perfectly lovely. Getting something to work and do what you need it to do is way more important at this learning stage than eloquence, I think :-). You’re doing great!