Sorted Union - Array.reduce() help

Here is my solution to the Sorted Union challenge from Intermediate Algorithm Scripting. I can’t help but feel that my code can be refactored to use reduce more effectively. Any advice would be appreciated.

Here is the text from the challenge:
Write a function that takes two or more arrays and returns a new array of unique values in the order of the original provided arrays.

In other words, all values present from all arrays should be included in their original order, but with no duplicates in the final array.

The unique numbers should be sorted by their original order, but the final array should not be sorted in numerical order.

function uniteUnique(arr) {
  var args = Array.from(arguments);
  var reducedArr = args.reduce(function(a, b) {
    return a.concat(b);
  });
  
  var results = [];
  
  for (var i = 0; i < reducedArr.length; i++) {
    if (results.indexOf(reducedArr[i]) === -1) {
      results.push(reducedArr[i]);
    }
  }
  
  return results;
}
1 Like

Check the intermediated solution here

Anyways going with just English, I would look at it this way,

  1. take the first array, then add the second array to it.
  2. Remove the duplicates from left to right
  3. You should be left with an array with the original order but duplicates removed.

So the trick would be to not sort the in ascending order which would make things more complicated/interesting.

@Rafase282 @raymeibaum I did it a bit different.

  1. define a new array
  2. cycle through arguments of arr
  3. push value into the new array if indexof value is not found

In that way you don’t have to bother about the order of the values.

Yeah thats how i did this too: