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]);
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)));