Sorted Union challenge, is there a way to do it without built in Array methods?

Sorted Union challenge, is there a way to do it without built in Array methods?
0

#1

Hello guys,

I’ve completed the Sorted Union challenge, this is my solution:

function uniteUnique(arr) {
var unique;
var result = [];

for(var i = 0; i < arguments.length; i++){
for(var j = 0; j < arguments[i].length; j++){
// console.log(arguments[i][j]);
result.push(arguments[i][j]);
// console.log(result);
}
}

unique = result.filter(function(elem,index,self){
return index == self.indexOf(elem);
});

return unique;
}

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

First I tried to solve this issue without any builtin array methods, but I could not come up with any ideas. So I checked google, how to solve this type of issue with array methods.(which array methods to use).

But I’m curious if this challenge can be solved without using methods like filter, reduce and the others. By this I mean, is there a way to compare the indexes inside the result array, and sort out the duplicates?

Thank you!


#2

You should re-create your own filter, reduce and indexOf methods. Then you will figure out how to solve the problem without using a built-in array.

function filter( callback ) {
  // your code
}

#3

Yes, that’s a good idea. But I think I will do the following:
create a function that checks values and if needed removes the duplicated values from the array. Something like this:

function checkRemove(a,b, arr){
   if(){ //check if item is duplicated
    //if item is already in result array, do nothing
   }else{
    //push item in to result array 
  }
 }

If I assume it right, I should call this function inside the loop ( for loop)? I have to think if I need two loops, or is just one enough.

Update 1:

So after checking google and trying to solve this for hours, I found a solution for this, which I think is very simple.

var arr = [ 1, 3, 2, 5, 2, 1, 4, 2, 1 ];
var newArr = [];

function checkAdd(arr){
   for(var i = 0; i < arr.length; i++){
      if (!(arr[i] in newArr)) {
            newArr.push(arr[i]);
        }
   }
   return newArr;
}
checkAdd(arr);

Basically, the checkAdd function checks if the arr[i] is not already inside the newArr. If it is not, it will add the arr[i] to the newArr. For me personally the in operator was new, as I have not encountered it previously.

Below you can find the full code:

function uniteUnique(arr) {
  var argumentsArr = [];
  var resultArr = [];
  
  for(var i = 0; i < arguments.length; i++){
     argumentsArr = argumentsArr.concat(arguments[i]);
  }
  
  function checkAdd(arr){
   for(var i = 0; i < argumentsArr.length; i++){
      if (!(arr[i] in resultArr)) {
            resultArr.push(arr[i]);
        }
   }
  }
  checkAdd(argumentsArr);
  
  return resultArr;
}

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

I hope that this will be helpful for someone. :slight_smile: