Skip to content

Instantly share code, notes, and snippets.

@rfprod
Last active April 22, 2017 15:59
Show Gist options
  • Save rfprod/104a29c875b220de17cc to your computer and use it in GitHub Desktop.
Save rfprod/104a29c875b220de17cc to your computer and use it in GitHub Desktop.
Sorted Union

Sorted Union

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 are sorted by their original order, but the final array is not sorted in numerical order.

A script by V.

License.

function unite(arr1, arr2, arr3, arr4) {
var baseName = "arr";
var nArr = [];
for (var i=0;i<arr1.length;i++){
for (var j=0;j<arr2.length;j++){
if (arr1[i] == arr2[j]){
arr2.splice(j,1);
}
}
if (arr3 !== undefined){
for (var k=0;k<arr3.length;k++){
if (arr1[i] == arr3[k]){
arr3.splice(k,1);
}
}
}
if (arr4 !== undefined){
for (var l=0;l<arr4.length;l++){
if (arr1[i] == arr4[l]){
arr4.splice(l,1);
}
}
}
}
var q = 0;
arr1.reduce(function(previousValue, currentValue, currentIndex, array) {
nArr.push(currentValue);
},0);
arr2.reduce(function(previousValue, currentValue, currentIndex, array) {
nArr.push(currentValue);
},0);
if (arr3 !== undefined){
arr3.reduce(function(previousValue, currentValue, currentIndex, array) {
nArr.push(currentValue);
},0);
}
if (arr4 !== undefined){
arr4.reduce(function(previousValue, currentValue, currentIndex, array) {
nArr.push(currentValue);
},0);
}
return nArr;
}
unite([1, 2, 3], [5, 2, 1, 4], [2, 1], [6, 7, 8]) ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment