Merge two arrays keeping only unique values (v9)

Revision 9 of this benchmark created by foo on


Setup

var arr1 = [2,4,5,8,9];
    var arr2 = [3,6,11];

Test runner

Ready to run.

Testing in
TestOps/sec
Tim's Solution
var merge = function (one, two) {
    var combined = [];
    while (one.length > 0 && two.length > 0) {
        var smaller = one[0] < two[0] ? one : two;
        combined.push(smaller.shift());
    }
    return combined.concat(one, two);
};

merge(arr1,arr2)
ready
Merge Solution 1
// merge


// [2,3,4,5,6,8,9,11]

var merge = function(arr1, arr2) {
  var result = [], next;

  while (arr1.length && arr2.length) {

    // if (arr1[0] <= arr2[0]) {
    //   result.push(arr1.shift());
    // } else {
    //   result.push(arr2.shift());
    // }
    result.push(( arr1[0] <= arr2[0] ) ? arr1.shift() : arr2.shift());

  }
  return result.concat(arr1).concat(arr2);
}

 
ready
Another Merge Solution
var merge = function(arr1, arr2) {
  var result = [], indexOne =0, indexTwo = 0;

  while (indexOne < arr1.length && indexTwo < arr2.length) {
   if (arr1[indexOne] <= arr2[indexTwo] ) {
     result.push(arr1[indexOne]);
     indexOne++
    } else {
     result.push(arr2[indexTwo]);
     indexTwo++
    }
  }
  return result.concat(arr1.slice(indexOne)).concat(arr2.slice(indexTwo));
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.