Skip to content

Instantly share code, notes, and snippets.

@martin-mok
Created January 11, 2020 22:34
Show Gist options
  • Select an option

  • Save martin-mok/f3077c7876cf2c1084496987ebbd4131 to your computer and use it in GitHub Desktop.

Select an option

Save martin-mok/f3077c7876cf2c1084496987ebbd4131 to your computer and use it in GitHub Desktop.
freecodecamp: Sorted Union

Description

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. Check the assertion tests for examples.

Tests

tests:
  - text: <code>uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1])</code> should return <code>[1, 3, 2, 5, 4]</code>.
    testString: assert.deepEqual(uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]), [1, 3, 2, 5, 4]);
  - text: <code>uniteUnique([1, 2, 3], [5, 2, 1])</code> should return <code>[1, 2, 3, 5]</code>.
    testString: assert.deepEqual(uniteUnique([1, 2, 3], [5, 2, 1]), [1, 2, 3, 5]);
  - text: <code>uniteUnique([1, 2, 3], [5, 2, 1, 4], [2, 1], [6, 7, 8])</code> should return <code>[1, 2, 3, 5, 4, 6, 7, 8]</code>.
    testString: assert.deepEqual(uniteUnique([1, 2, 3], [5, 2, 1, 4], [2, 1], [6, 7, 8]), [1, 2, 3, 5, 4, 6, 7, 8]);

Solution

Offical soln:

function uniteUnique(arr) {
  return [].slice.call(arguments).reduce(function(a, b) {
    return [].concat(a, b.filter(function(e) {return a.indexOf(e) === -1;}));
  }, []);
}

My soln:

function uniteUnique(...arrs) {
  return arrs.reduce(
    function(newArr,arr){
      for(const e of arr){
        if(newArr.indexOf(e)===-1){
          newArr.push(e);
        }
      }
      return newArr;
    });
}

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

Other solns:
Algorithm Scripting -- Sorted Union

function uniteUnique() {
  const args = Array.prototype.slice.call(arguments);

  return args.reduce((a, b) =>
    [...a,
    ...b.filter(e => a.indexOf(e) < 0)]);
}

Sorted Union - freeCodeCamp using Modern JavaScript #10

const flatten = array => array
  .reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []);

const uniteUnique = (...arrays) => Array.from(new Set(flatten(arrays)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment