Sorted Union help

function uniteUnique(arr) {
  var args = Array.prototype.slice.call(arguments, 1);
  var newArr = [];
  if(args.length <= 2) {
   newArr = args[0].concat(args[1]);
  } else {
    newArr = args[0].concat(args[1], args[2]);
  }
   for(var i = 0; i < newArr.length; i++) {
    if(arr.indexOf(newArr[i]) !== -1) {
      delete newArr[i];
    }
  }
  newArr = newArr.filter(function(val){
    return val !== null;
  });
  return arr.concat(newArr);
}

uniteUnique([1, 2, 3], [5, 2, 1]);

Why is this test returning null as the final value? Shouldn’t the filter be getting rid of it?

When I ran the test, it gave me undefined as the final value rather than null. Have you tried making the filter return != undefined?

No. I will try it though.

It works thanks. Can you explain why I should test against undefined as well as null?

These are the seven built-in types in javascript: null, undefined, boolean, number, string, object, & symbol.

Null and undefined might seem the same but I believe the difference is that a value is set to null intentionally. That is, you the coder would set the value to null to indicate that the variable (or whatever) is intentionally blank.

In case you’re wondering, the reason you’re getting undefined in the first place is because of how you declared your args variable.
Array.prototype.slice.call(arguments, 1);
This tells javascript to:

  1. Create a new array
  2. Discard the first argument passed
  3. Place all the other arguments in that new array.

So when passed the arguments ([1, 2, 3], [5, 2, 1]), args becomes [[5, 2, 1]].

That means when you do this:
newArr = args[0].concat(args[1]);
You are concatenating [5,2,1] with a non-existent (undefined) value.

1 Like

I believe it is that null is an empty value, like a void, and undefined is when there is no assigned value at all.

var a; // returns undefined

No value was assigned. This is the case when you target non-exsting values.
null is : none of the above
undefined is: 404 Not Found

I was going to say this, but I had the feeling your second response was what he meant, and I didn’t understand the example this was from well enough.