Review my code Sorted Union

Is it nice ? or can be improved ?


function uniteUnique(arr,...arg) {
for(let i in arg)
{
  arr.push(...arg[i]);
}
for(let i=0;i<arr.length;i++)
{
  for(let j=i+1;j<arr.length;j++)
{
  if(arr[j]==arr[i])
  {
    arr.splice(j,1);
  }
}

}
return arr
}
console.clear();
console.log(uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]));

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sorted-union

Hi!

Two things: use tabulation and spaces between operators. Also it’s a nice habit to comment your code:

/*******************************
* Description of the function  *
*******************************/
function uniteUnique(arr, ...arg) 
{
  for (let i in arg)
  {
      arr.push(...arg[i]);
  }

  for (let i = 0; i < arr.length; i++)
  {
    for (let j = i+1; j < arr.length; j++)
    {
      if (arr[j] == arr[i])
      {
        arr.splice(j,1);
      }
    }
  }

  return arr;
}
1 Like

cool thanks :grin: i’ll keep this in mind and what u wrote is looking better than mine.

1 Like

You’re welcome! A good way to practice is to think that everyone that reads the code must understand what it does.

1 Like

Hi @coderharshit

I don’t know if you have explored code complexity and big-O, but since you have a for loop running inside another for loop (nested), generally speaking, the time it takes to run your code is much longer than if you could come up with a solution that doesn’t have a nested for loop.

I came up with the following:

Spoiler
function uniteUnique(arr, ...arg)
{
    let newArr = [];
    for (let i of arg)
    {
        arr.push(...i);
    }
    for (let i = 0; i < arr.length; i++)
    {
        console.log("is " + arr[i] + " present in the newArr already? " + (newArr.indexOf(arr[i])));
        console.log("does newArr.indexOf(" + arr[i] + ") == -1? " + ((newArr.indexOf(arr[i])) == -1));
        if ((newArr.indexOf(arr[i])) == -1)
        {
            console.log("pushing " + arr[i] + " onto newArr which already contains " + newArr);
            newArr.push(arr[i]);
            console.log("\n");
        }
    }

    return newArr;
}

console.log(uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]));
console.log(uniteUnique([1, 3, 2], [1, [5]], [2, [4]]));
console.log(uniteUnique([1, 2, 3], [5, 2, 1]));
console.log(uniteUnique([1, 2, 3], [5, 2, 1, 4], [2, 1], [6, 7, 8]));