FCC Advanced Algorithm Scripting Challenge – ‘Symmetric Difference’

Let’s tackle another Free Code Camp advanced algorithm – ‘Symmetric Difference’.  The challenge here is to ‘create a function that takes two or more arrays and returns an array of the symmetric difference ( or ) of the provided arrays.’

The symmetric difference of two sets of elements is the set that occurs in either one of the two sets, but not both (i.e. the symmetric difference of [1,2,3,4] and [3,4,5,6] is [1,2,5,6]).  For more reading on symmetric difference, check out this wiki page.

Free Code camp gives us the following as a starting point:

This is another case where we have to write a function for which we need to handle an unknown number of arguments.  To accomplish this, we’ll be using the arguments object.  I’ve covered the arguments object in a previous post, ‘Seek and Destroy’.  If you are unfamiliar with or would like a refresher of the arguments object, please check it out.

One of the helpful hints FCC provides us with is a link to the Array.prototype.reduce() method.  The arr.reduce method is a great way to cycle through and apply a function to each element of an array.

The arr.reduce method takes 2 arguments, a callback function (which will be applied to each element of the array) and an initial value (the element to provide as the first argument to the first callback function call – see here for more).

If you’re new to JavaScript, or somewhat unclear of what a callback function is, JavaScriptIsSexy.com has an excellent post on callbacks.

The callback takes a possibility of 4 arguments – previousValue, currentValue, currentIndex and array.  This is important, as it means when we write our callback function, we will have access to these 4 values within the function (for further clarity on exactly what the four values are, check out the MDN link mentioned previously).

I think we should break down this challenge into two main problems.  We need to:

  • Write a function that returns an array of the symmetric difference (⊕) between two given arrays
  • Use this function to handle an unknown number of arguments. For example:
    • find (arg1 ⊕ arg2)
    • if there’s an agr3, find arg3 ⊕ (arg1 ⊕ arg2)
    • continue for argX

At this point, I’m going to start discussing my solution to the problem.  If you’re working through FCC, I’d suggest attempting a solution on your own given what we’ve discussed above. Otherwise, proceed on…

Spoilers_ahead

Let’s start by writing the function we’ll use to calculate the symmetric difference between two arrays.

In other words, we need to write a function that receives two arrays as arguments, then returns an array of the numbers that are in one of the argument arrays, but not both.

One way to do this is to

  • create a new empty array (curDiff) to store the symmetric diff
  • use arr.reduce() to cycle through each array (need to compare each array against the other, not just one against the other)
  • in the callback function of arr.reduce
    • check if an element is in the other array or in the curDiff array (to prevent duplicates in curDiff)
    • if not – push element to curDiff
      • hint – arr.indexOf() will return -1 if the given element is not found
  • return curDiff

Here’s the JavaScript code:

We now have a function (findSymDiff()) that we can use within our main function to get the symmetric difference between two arrays.  We now have to set up the logic to handle an unknown number of parameters received by our main function.

Our logic (using the arguments object) can look something like this:

  • create new array (symDiff) to store the array returned by findSymDiff()
  • compare arguments[0] to arguments[1] using findSymDiff()
  • cycle through argument[]
    • compare symDiff to arguments[x]

To accomplish this, we can set up a simple for loop.

If we set

we can call

in our for loop starting at i=1 and loop while i<arguments.length.

Then all we have to do is return symDiff!

Here’s how everything looks when we put it together:

This solution passes all of the FCC test cases.

Thanks for reading, feel free to leave comments or additional solutions below.  And if you’re working through Free Code Camp, hopefully this helped straighten out the code.

-Jeremy

 

FCC Advanced Algorithm Scripting Challenge – ‘Map the Debris’

Today we’ll work through our first Free Code Camp advanced algorithm challenge called ‘Map the Debris‘, which will give us some exposure to working with objects.

This challenge asks us to ‘Return a new array that transforms the element’s average altitude into their orbital periods’

It further tells us that the array will contain objects in the following format:

FCC also points us to this wikipedia page to read about orbital periods.

Finally, it gives us the following as a starting point:

I think, given the limited amount that we’ve spent on objects here at crookedCode, we should start with a brief overview.

I’m not going to reinvent the wheel and write thousands of words on JavaScript objects when so many others have covered it much better than I ever could.

I will, however, point you to, and urge you to read, chapter 4 and chapter 6 of Eloquent JavaScript.  This will take some time, especially if you work through the examples (which I highly recommend) but you’ll have a much greater understanding of objects once you’re done.

Some basics about JavaScript Objects:

Here, I’ll cover objects in enough detail to get us through this FCC algorithm.  If you’ve read the chapters mentioned above, this should all be review.

In JavaScript, objects are basically a collection of properties that can be wrapped together and stored in one variable. Properties consist of {key: value} pairs.

I think the best way to demonstrate this concept is through an example.  I don’t know why, but let’s say I wanted to create myself as an object…  It might look something like this:

This example shows 4 sets of key: value pairs, the first of which is – firstName: ‘Jeremy’ – with firstName being the ‘key’ and ‘Jeremy’ the ‘value’.  All 4 of these properties are now stored under the variable – me.

I can access and manipulate the properties through dot notation (bracket notation can also be used, but we’re going to stick with dot notation throughout this exercise).

In the example below I will access my age and change it to 21 (I know, I know, wishful thinking….).

As you can see when I logged the ‘me’ object to the console, the age has now been changed from 41 to 21.

We’ve seen object properties above as strings or numbers, but they can really be any data type, including other objects or functions.  When a property in an object is a function, it is said to be a ‘method’ of that function.  I’ll demonstrate how we can add new properties to objects below by giving ‘me’ a hair color property and a method.

Ok, suffice to say, this is only scratching the surface with objects in JavaScript, but I think we can move on to solving ‘Map the Debris’.

Before going any further I feel I should say there are many ways to solve this problem…  Some of them, I’m sure, are much more ‘slick’ than mine. This is the solution, however, that I wrote and am providing here as a working solution in an attempt to help anyone who is struggling or looking for a different perspective.

Solving ‘Map the Debris’

We know from the problem description that we will be getting an array of objects as an argument, and that each object in this array will have name and avgAlt properties.

We need to take each of the avgAlt properties, calculate the orbital periods (based on the equation given to us on the Wikipedia page referenced above), and return an array of objects that contain name and orbitalPeriod properties.

First things first, how do we calculate an orbital period?  Below is the formula given on Wikipedia.

orbperiod for crookedcode

This equation might look a little intimidating if it’s been a while since your last math class, but we have all the elements we need.  We just have to rewrite the equation in JavaScript and fill in the correct values.

Fortunately, there’s a Math object in JavaScript that has all the methods associated with it that we’ll need (i.e. pi=Math.PI, squareroot=Math.sqrt(), exponents=Math.pow(base,exponent).  We’ll also use Math.round() to round our answer to the nearest whole number as required by the challenge.

My logic for setting up the solution was as follows:

  • Write a function that solved the orbital period given the avgAlt (let’s call the function findOrbPeriod)
  • Then write a loop to cycle through the array of objects that
    • adds an orbitalPeriod property with a value calculated using the findOrbPeriod function.
    • deletes the avgAlt property for each object in the array.
  • Return the array.

If you’re working through Free Code Camp, I would suggest taking what we just talked about and try to solve the equation on your own.

Otherwise, proceed on…

Spoilers_ahead

Let’s start by writing the function that will solve the orbital period.

As you can see, we use the avgAlt plus the earth’s radius for ‘axis’ in the equation.  The second line in the function is the orbital period equation listed above, only written using the JavaScript Math object.  Finally, we return the orbital period so we can use this function to populate the new orbitalPeriod property of each object.

Now we can tie everything together by cycling through the array of objects (arr) and calling the function we just wrote (findOrbPeriod()) for each object.

As you can see, the for loop adds an orbitalPeriod property to and removes the avgAlt property from each object in arr.  Then all we have to do is return arr.

There we go!!  We made it through our first  FCC advanced algorithm.  Hopefully this helped straighten out the code for you, feel free to leave any questions or comments below.  Until next time…

-Jeremy

Front End Certificate at Free Code Camp – Complete!!

Five months and one day after I discovered Free Code Camp, I’ve completed my Front End Certificate.

frontEndCert

It took a little longer than I had originally planned, but considering that in addition to learning HTML, CSS and JavaScript from scratch, I maintained a full time job and tried to spend (at least some) time with my family (including coaching a season of baseball), I’m pretty happy with the accomplishment.

A couple thoughts on the process….

When I discovered Free Code Camp, I rolled up my sleeves and began the front end development section with tunnel vision, focused only on completing the certificate.   Along the way, my focus broadened… I began to realize that this process isn’t just about completing a certificate, but becoming a strong developer.

To that end, I searched for additional resources to supplement the Free Code Camp curriculum.  I covered a lot of these resources in a previous post, but mostly it involved listening to podcasts, reading books, watching YouTube videos and practicing algorithms.

I also started this blog.  If you would have told me before I started this process that I would start a blog on learning to code, I would have labeled you crazy…

I’m an introverted guy and generally keep my thoughts to myself, so expressing myself in these posts isn’t exactly second nature. I think, however, that doing so has significantly enhanced what I’m getting from this process (and hopefully helped at least a couple others in return).

I’ve also found that trying to explain the solution to an algorithm is, in many ways, much harder than writing the solution itself!  I think this has certainly helped strengthen my coding skills and plan to continue working through the solutions to many of the freeCodeCamp algorithms and projects here at crookedCode.

So, if you find yourself getting frustrated with your progress in your own learning to code journey, take a step back and ask yourself what else you could be doing to broaden your learning experience.

And finally, I want to say – Learning to code is hard!  

This journey has been difficult in many ways I could not have predicted at the onset. First, of course, learning a new skill (any new skill) can be difficult.  Coding is certainly no exception, in fact, I’d argue just the opposite.  

I feel the difficulty is often overlooked in the many articles (at least the ones I’ve read) that proclaim everyone can learn to code.  Many of these articles fail to mention that it’s going to take a lot of work and a lot of extremely frustrating, trying moments, especially if you’re teaching yourself.  

I’m not arguing against the idea that people should learn to code…  If learning to code interests you, then by all means, let nothing stand in your way. Before you start, however, make sure that it’s something you really want to do and make sure you’re prepared to commit the time and mental energy to accomplish your goal.

In addition to the difficulty inherent to learning to code, many other aspects of the journey add to the difficulty…

Time management has been a big one for me.  Keeping a full time job, having a wife and two active sons and learning to code is a very full plate.  Through most of baseball season, I just coded whenever I could fit it in the schedule…

It seemed like there was something going on every night and throughout the weekend, so whenever there was a break, I would try to put some work in.  I’ve got to say though, that pace is unsustainable if you value your mental health and the happiness of your family.

Since baseball has finished, I have blocked off two evenings and one day on the weekend that I devote to learning to code.  Everything else (at least when I’m not at my full time job) can be spent with family or catching up with stuff around the house.

If you are learning to code and have other personal commitments, I highly recommend blocking off a schedule of when you plan to work. Otherwise, you always feel like you should be working and everything else in your life takes a back seat, and suffers because of it….

Of course, there are other things like maintaining self-confidence, battling impostor syndrome, deciding what to learn, setting up a development environment, etc., etc. but this post is already longer than I had planned.  Just know that if you are struggling in your journey to learn to code, you are not alone, there are plenty of us out there in the same boat.

So, if you’re still reading this, thank you and good luck on your own journey.  I’ll keep posting here at crookedCode to try to make things easier for those that actually read it.   As for right now, I’m off to start the back end development certificate at Free Code Camp…

-Jeremy

FCC Intermediate Algorithm Scripting Challenge – ‘DNA Pairing’

 

Today, we’ll cover freeCodeCamp’s Intermediate Scripting Challenge ‘DNA Pairing‘.  The challenge here is to write a function that accepts a string of characters and returns a 2D array of matched base pairs.

If you’re not caught up with your molecular biology, here’s a quick lesson…

Molecular Bio 101 (mostly not needed to solve algorithm)

By Zephyris at the English language Wikipedia, CC BY-SA 3.0
By Zephyris at the English language Wikipedia, CC BY-SA 3.0

DNA is the double stranded nucleic acid that carries your genetic information.  Each single strand is composed of units called nucleotides, of which, there are four – cytosine (C), guanine (G), adenine (A) and thymine (T).  In double stranded DNA, these nucleotides bond in specific base pairs, A with T and C with G.

DNA stores all kinds of biological information and make up our chromosomes, which, in turn, make you who you are…  Enough bio, let’s get back to solving the algorithm….

Bio Class Dismissed…

As we get into the intermediate and advanced algorithm challenges, each challenge will have multiple (even many) approaches to a solution.  My plan with Crooked Code is to explain the solution that I used, then search for solutions used by others in order to illustrate the various ways an algorithm can be written.

This is what freeCodeCamp gives us as a starting point for ‘DNA Pairing’:

The instructions provided for this challenge tell us that we’ll be getting a string as an argument and we must return a 2D array that matches up each element (letter) with it’s base pair counterpart.

Let’s get started working on a solution…

I started by ‘splitting’ the string argument into an array using string.split() method.  I covered string.split() in depth here.   I also created some variables that we’ll use later in the function.  My ‘pairElement’ function now looks like:

We now must scroll through ‘singleArr’ and pair up each element with it’s matching pair.  We can use a for loop to scroll through the array, but how can we match up the pairs?

A bunch of if/else statements would work but a switch statement is a better option here.  A switch statement will evaluate a given expression, then transfer control to the case that matches the outcome of the expression.

I’ve included the syntax of a switch statement written by mozilla in order to make the explanation easier.

In our case, the expression will be just a letter, as will each case value.  We can then write a statement to be executed for each individual case.

To sum up the logic for our algorithm…

  • split the given string into an array
  • loop through array and match each element with it’s pair
  • ‘push’ each new pair into 2D array
  • return 2D array

At this point, we’ve covered everything needed to solve the ‘pairElement’ function.  If you’re working through the freeCodeCamp curriculum you may want to go try to solve it on your own, otherwise, read on…

Spoilers_ahead

Here’s the solution to the ‘DNA Pairing’ challenge that I came up with:

The freeCodeCamp wiki page (written by @Rafase282 and @sabahang) provides 2 solutions to this algorithm challenge.  The first, ‘basic’, solution is very similar to mine, using a switch statement, so I won’t include it for the sake of redundancy.

The second, ‘intermediate’, solution uses an object, and we haven’t really covered objects in much detail here at Crooked Code.  I’ll include the code below so we can see a second, very different solution, but won’t provide an explanation, as objects are far too big of a topic to cover at the end of this post.

You can see an explanation to this solution at the wiki page.

That’s it for now, hopefully this helped straighten out the code…

-Jeremy

FCC Intermediate Algorithm Scripting Challenge – ‘Boo who’

This post will cover freeCodeCamp’s intermediate algorithm scripting challenge ‘Boo who’.

‘Boo who’ challenges us to write a function that checks if a given argument is classified as a boolean primitive.  If so, return true, if it’s anything else, return false.

The solution, once written, is quite simple but there are a few key concepts we have to understand before we can get there.

Here’s what FCC gives us as a starting point:

Now, we have to figure out…  What the hell is a boolean primitive?

First, let’s consider what boolean means?  Boolean is a word used in both math and computer science.  In computer science, it generally refers to a data type or a variable that can have only one of two values, usually true or false.

Boolean variables are useful in controlling the logic of an algorithm and are generally used in conditional statements such:

Second, what does primitive mean?  Mozilla, as always, gives a pretty good description of a primitive.  Basically, Mozilla tells us a primitive value ‘is data that is not an object and has no methods.’

Tangent on Primitive Types vs. Reference Type

According to the latest ECMAScript standard, JavaScript has 7 data types. 6 primitive types which are string, number, boolean, null, undefined and symbol and one reference type – object.

The difference between the two types becomes confusing when you consider that JavaScript provides constructor functions that allow you to wrap boolean, number and string values as objects, which changes them from primitive to reference type.

Consider the following:

Problems start to arise if you try to use a string object like a string primitive.  Keep in mind that a string object is still an object, and behaves like one.

For instance:

Given that JavaScript will allow you to use the methods associated with an object prototype on the primitive values (example below), it is best to use primitive types whenever possible.

FYI, Effective JavaScript by David Herman has a good section on why primitive types should be preferred to using object wrappers and I derived some of my examples above from those found in his book.

Ok, enough about Primitive Types, hopefully this has been more than enough info to solve ‘Boo who’.

End of Tangent

Check out the Mozilla link above for further explanation of primitive values (or this one for info on the Boolean object), but for our purposes in solving ‘Boo who’ we now know that the only boolean primitives are true and false.

So, now we have to fill in the booWho function above, checking if bool equals true or false.  In doing so, we’ll use the strict equality operator (===) vs. the loose equality operator (==), as the latter will convert the two values to a common type before checking equality, which is not what we want.

At this point, we’ve gone over all the tools you’ll need to write the booWho function, so if you’re working through the freeCodeCamp curriculum you may want to go try to solve it on your own, otherwise, read on…

Spoilers_ahead

Here’s the solution to ‘Boo who’ that I came up with:

As you probably know, || is the logical operator ‘or’ in JavaScript, so this function will return true if bool equals true or false.

The freeCodeCamp wiki provides an even shorter solution using the ‘typeof’ operator, written by Rafase282.

Both solutions solve the ‘Boo who’ algorithm challenge and pass all the test cases at freeCodeCamp.

That’s it for now, hopefully this helped straighten out the code…

-Jeremy

My Learn-to-Code Journey: 3 months in…

I started my learn to code journey in late February, 2016,  when I signed up for freeCodeCamp.  So it’s been about 3 1/2 months and I figured this was as good a time as any to share my thoughts, progress, tools that I’ve found valuable, etc, etc.

First, a little background on what led me to this journey…

I’ve been doing drug discovery/pharmaceutical research for nearly 20 years.  Last year, I found out that my job was moving to a different part of the country and for many reasons, not the least of which was apprehension over relocating my two sons, we decided not to make the move.

After a lot of soul searching (and driving my wife crazy), I decided to shift my career and learn to code.  In fact, the real light bulb moment was reading Derek Sivers post ‘Should you learn programming? Yes.’  It’s where I discovered freeCodeCamp and everything seemed to snowball from there…

Stumbling on that Sivers post was just what I needed and I’ve since become a huge fan of his.  If you haven’t read or watched anything by Derek, do yourself a favor and check out his site. He has a unique perspective on life that’s completely refreshing when compared to most of what you encounter in the world today.

Ok, enough background…

Looking back at the last 3 months, it’s hard to put into words everything I’ve gone through in learning to code.  So far the journey has been fun, frustrating, time consuming, enlightening, tiring, exciting, stressful, rewarding, humbling…  Basically, it’s been a roller coaster ride.

It seems like one minute I feel like I’m on top of the world and that I can do and create anything.  Then the next minute I feel like a total idiot and don’t know anything.  Then genius again, then an even bigger idiot than before…  You get the picture.

Free Code Camp Update

For the time being, I still have a full time job (and coach my son’s baseball team) so I don’t have as much time as I’d like to devote to coding.  I’ve put in a lot of late nights and weekends and, despite the two huge time commitments mentioned previously, feel like I’ve been able to make a ton of progress.

I’m nearing completion on the Front End Development Certificate at freeCodeCamp.  I’ve completed all of the Algorithm Scripting Challenges and most of the Development Projects.  The only projects that I have left are to finish my Tic Tac Toe game, then build a Pomodoro Clock and a Simon game.  These, obviously, will take some time, but I should get them done within the next month or so.  You can check out my projects on my Codepen page.

I’ve also started on the Back End Development Certificate.  The first lesson was on Git, then you get right in to Node.js and Express.js.  The biggest thing I’ve learned so far on the back end (in addition to reinforcing once again that I’m an idiot) is that I need to become comfortable in the command line.

Thoughts on Free Code Camp thus far..

I feel that freeCodeCamp, in providing projects with increasing levels of difficulty, provides a great path to follow in learning to code. On the other hand, I feel some of the learning modules are lacking.  For instance, having gone through the git and npm learning modules at the beginning of the back end certificate, I don’t feel like I learned much and have little more understanding of how to use them now than when I started.

I don’t think, however, this is a negative for freeCodeCamp (and not sure if it was purposefully constructed this way or not).  After all, what is the purpose of freeCodeCamp??  To prepare you to become an employable full stack web developer?

Part of this whole process is learning to become resourceful and knowing where and how to look for answers when you run into problems. Something at which I’ve become increasingly skilled.  Is it frustrating to pause in the middle of a project to go look up how to code something? Absolutely.  Over and over again?  Yup…  But in the end, I’ll be a much stronger programmer for it.

In addition to Free Code Camp

In a previous post, I mentioned some of the resources I’ve been using as I make my way through the front end cert at FCC.  In addition to these, I’ve been broadening my knowledge of software development in general through the use of other sites, listening to podcasts and constantly searching for ways to learn (including starting a blog!!).

One of the other sites I discovered is Codewars.

Having finished all 3  algorithm sections at FCC, I was looking for a way to further my algorithm solving skills.  I haven’t used the site extensively yet, in fact, I’ve only worked through about 4 or 5 ‘kata’ (which is what Codewars calls their algorithm problems), but I plan on going back on a fairly regular basis to stay fresh with Javascript as I work through the backend at FCC.

After you solve a given ‘kata’ , you can see the solutions of previous users. In fact, I’m planning on writing one of my next posts on an embarrassingly long solution I wrote that others had solved in one line. Ha!  Live and learn I guess…

Like I said before, I’ve also gotten in the habit of listening to podcasts on my commute to and from work.

Some of my favorites, in no particular order are: JavaScript Jabber, CodeNewbie, Coder Radio, Eat Sleep Code, Becoming a Data Scientist, CodePen Radio, Simple Programmer, Software Engineering Daily and anyone that interviews either Seth Godin or Derek Sivers (The Tim Ferriss Show has great interviews of them both).

More Learning Tools

As I said before, I’ve used a lot of the tech websites (Mozilla, Stack Overflow, W3schools, etc) to learn as I went through the Front End course. I’ve decided to try something different on the back end.  I signed up to audit a Node.js course on coursera.  I can’t give any feedback on how useful the course is or whether it will help with the back end cert at FCC, as I just signed up for it yesterday, but I’ll be sure to write a future post about it.

While listening to the tech podcasts mentioned above, I kept hearing, over and over, the advice to create a blog.  So I did…  And I’m happy I did.

I have no idea how many people this blog will reach in the end, but one of the great benefits of it has been in reinforcing everything I’ve been learning.  I know one of the best ways to really learn something is to try to teach it to others, but I didn’t realize just how true this was.

Even in writing a post about the solution to a Basic Algorithm Scripting challenge, I’ve really had to solidify my knowledge of the JavaScript language and understand the methods and data types that I’ve used.  So, if you want to check if you really understand something, try explaining it to someone else…

As for advice on creating the blog itself, Simple Programmer (John Sonmez) created a great, and free, blogging course that walks you through the steps of creating a blog.  If you’re considering creating your own blog, I recommend signing up for his course, it’s what I used to get started.

Damn this is post is long…

On the remote chance that anyone has stumbled on this blog, and on the even more remote chance that you’re still reading, let me leave you with this..

If you’re on your own journey in learning to code, you are going to go through some rough patches and getting though those times are going to be extremely difficult.  My advice is this…  Don’t take the easy way out, it’ll just lead to more rough patches.

What I mean by that is if you are looking to solve problem x, or write some code to accomplish y, the easy way would be to google it, find some code that someone else has written, copy and paste it into your project and move on…  This may solve your short-term problem, but will get you nowhere in the end.

I’m not saying don’t use google to solve problems or look up ways to write something in whatever language you are using at the time.  I do that all the time.  What I am saying is take the time to learn how the code is written, or the logic behind the algorithm and go write your own solution…

That’s all for now, I’m off to continue my journey…

-Jeremy

 

 

 

 

 

 

 

FCC ‘Seek and Destroy’

This post will work through ‘Seek and Destroy’, one of freeCodeCamp‘s basic algorithm scripting challenges.  This challenge will help us introduce the Arguments object and callback functions.

The Seek and Destroy challenge states that ‘provided with an initial array (the first argument in the destroyer function), followed by one or more arguments’ we need to write a function that will remove the values of all the arguments given after the initial array, from the initial array.

Sounds confusing, I know…  Let’s visualize it to clear things up.

 

One of the major problems we have lies with ‘followed by one or more arguments’…  If we don’t know how many arguments there will be, how do we write a function to handle them?

The answer to that comes in the form of the Arguments object.  JavaScript provides a local variable ‘arguments’ that acts like an array with an element for each argument passed to the function.  You access the arguments just like you would an element of any other array like so:

The arguments object makes solving this algorithm challenge much easier.  Looking forward at ways to solve this problem, we need to a) access the arguments we need to delete from the initial array and b) somehow remove those arguments from the array.

Storing arguments for easy access

The first thing we’ll do is create a new array and store all the arguments (other than the initial array) in it.

As you can see, arguments can be treated like any other array…  Here, we used the length property and looped through arguments (starting at element 1 so as to avoid the initial array, which will be passed in as the first argument, or arguments[0]).  Setting it up this way will handle any number of arguments passed to the destroyer function.

The push() method in JavaScript is used to ‘push’ new elements on to the end of the calling array.

Tools we’ll need to remove arguments from the array

In order to remove the arguments from the initial array, we will use the filter() method.  The filter method introduces a concept we haven’t talked about here at CrookedCode: the callback function.

A Quick note on functions in JavaScript

The power of functions, and what they allow you to do, are core to successful JavaScript programming.  Functions can be passed to and returned from other functions.  They can also be stored as variables.

A function that accepts another function as an argument is called a higher-order function, whereas, the function that is passed as the argument is called a callback function.  The Eloquent JavaScript chapter on functions is a great tutorial on the use of functions in JavaScript.

Eloquent JavaScript also devotes an entire chapter to higher-order functions.  I highly recommend reading and working through the examples in both of these chapters.  If you’re looking for something a little quicker, JavaScriptissexy.com has an excellent article on understanding callbacks and higher order functions.

The filter() method accepts a callback function and performs that callback on every element in the calling array.  If the callback returns true for a given element, that element is kept.  If the callback returns false, obviously, that element is not kept.

As stated above, filter() calls the callback function on every element of the calling array, but it does not mutate that array.  Therefore, you must save the kept elements as a new array.

The one final tool we’ll need before we try to solve this algorithm is the array.indexOf() method.  indexOf() will return the first index at which a given value is found.  If the given value is not found, indexOf() returns -1.

Putting it all together…. (finally)

We’ve already created argArr[] to hold the values that we need to delete from the initial array.  We now need to write a callback function for filter() that will return true if we want the element to stay and false if we want to delete that element.

We know that indexOf() will return -1 if a given value is not found.  We also know that we want to keep elements of the initial array that aren’t found in argArr[].  So, for each element of the initial array, lets call argArr.indexOf(), and return true for values of -1.  Therefore, we’ll be returning true for (and keeping) values that aren’t in argArr[].

Like so:

Wow…  This post covered a bunch of stuff we haven’t previously gone over here at CrookedCode, hopefully this helped straighten out the code for you.  See you next time…

-Jeremy