Sorted Union - How could I have done this better?

Sorted Union - How could I have done this better?
0

#1

Just finished doing the Sorted Union Challenge. I got through it with a few for loops, but I feel like theres a more effective way i could have gotten the same results using methods and using less code… any ideas?

function uniteUnique(arr) {
  var newArr = [];
  // push first array to newArr
  for (var i=0;i<arguments[0].length;i++) {
    newArr.push(arguments[0][i]);
  }
  //compare new arr to next arrys, push the values that are not already in newArr
  //loop over arguments arrays
  for (var j = 1;j<arguments.length;j++) {
    //loop over individual arrays
    for (var k = 0;k<arguments[j].length;k++) {
      if (newArr.indexOf(arguments[j][k]) === -1) {
        newArr.push(arguments[j][k]);
      }
    }
  } 
  return newArr;
}

#2

Like this :wink:

function uniteUnique() {
  let newArr = [];
  [...arguments].forEach(i => i.forEach(j => newArr.indexOf(j) === -1 ? newArr.push(j) : j));
  return newArr;
}

Shorter code doesn’t always mean faster code (for loop is considered pretty fast).


If you want to learn how to write a short code I highly recommend you to join codewars and go through 8 kuy and 7 kuy level katas and after solving each kata look at other’s solutions and try to understand what they did there (go through older katas first - they have more solutions, more comments, lesser bugs etc.).

Also 8 kuy and 7 kuy challenges cover fundamentals and by solving them you will see which part of the language you should pay attention to.