FCC Bonfire Series 127: Sorted Union

This next bonfire challenge is a nice way of getting to know the arguments object. The arguments object is a local variable available within any function and contains an array of the arguments provided. Here’s an example:

function foo() {
  for (var i = 0; i < arguments.length; i++) {
    console.log(arguments[i]);
  }
}

foo('b', 'a', 'r', [0, 1, 2]); //-> b, a, r, [0, 1, 2]

The is something that must be on our minds at all times, although the arguments object seems to be an array and even has a length method (and callee and caller, you can read about them here) it actually isn’t, so no Array methods are available within it (say filter, reduce, forEach, etc).

Now that that’s out of the way, let’s get to it. We must write a function that given any number of arrays as arguments, it returns a single array containing unique values in the same order as the originally provided arrays:

unite([5, 6, 7], [2, 3, 5]); //-> [5, 6, 7, 2, 3]
unite([1, 2, 3], [5, 2, 1, 4], [2, 1]); //-> [1, 2, 3, 5, 4]

There are quite a few ways of getting this done, we’ll go for the most simple solution, and I will let you come up with something else.

We are going to start by declaring a new empty array (were the end result is going to get stored). Then, we’ll loop over each array in the arguments object and push each unique item into our newly created array.

function unite() {
  var newArray = [];
  for (var i = 0; i < arguments.length; i++) {
    for (var j = 0; j < arguments[i].length; j++) {
      if (newArray.indexOf(arguments[i][j]) < 0) {
        newArray.push(arguments[i][j]);
      }
    }
  }
  return newArray;
}

As you can see, we are looping over the arguments object, and each individual array inside the arguments object. We check if each value is present in the result array with indexOf, and then push it if its unique. Pretty simple right?

How about you get functional and use reduce (or filter) to come up with a solution?