Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In PHP exists a function array_diff (http://php.net/manual/de/function.array-diff.php) which returns the difference of two arrays. I have tried the implement my own version in JavaScript.

Any feedback is welcome. :)

function getArrayDiff(a, b) {
  var ret = [],
      merged = [];

  merged = a.concat(b);

  for (var i = 0; i < merged.length; i++) {
    // When the element is contained ONLY
    //   one time then the search from
    //   left returns the same value as
    //   the search from the right.
    if (merged.indexOf(merged[i]) ==
        merged.lastIndexOf(merged[i])) {
      // ... in that case the element
      // is pushed to the result array.
      ret.push(merged[i]);
    }
  }

  return ret;
}

// -- Test ----------
a = [2, 4, 8, 16, 32];
b = [2, 4, 32, 64, 128, 256];

console.log(getArrayDiff(b, a));

Live Demo on CodePen: http://codepen.io/mizech/pen/GpVMEd

share|improve this question
up vote 1 down vote accepted

You can use Array#filter to get elements from array which are not present in other array.

var a = [2, 4, 8, 16, 32],
    b = [2, 4, 32, 64, 128, 256];

// Define custom method on Array prototype
// Pass the array as parameter
Array.prototype.diff = function (arr) {

    // Merge the arrays
    var mergedArr = this.concat(arr);

    // Get the elements which are unique in the array
    // Return the diff array
    return mergedArr.filter(function (e) {
        // Check if the element is appearing only once
        return mergedArr.indexOf(e) === mergedArr.lastIndexOf(e);
    });
};

// How to call?
var diff = a.diff(b);

console.log(diff);
document.write('<pre>' + JSON.stringify(diff, 0, 4) + '</pre>');


Shorter version:

var diff = array1.concat(array2).filter(function (e, i, array) {
    // Check if the element is appearing only once
    return array.indexOf(e) === array.lastIndexOf(e);
});
share|improve this answer
    
Here is JSPerf Test(Not reliable) – Tushar Nov 30 '15 at 10:54
    
Awesome. Thanks a lot. – michael.zech Nov 30 '15 at 10:58

Note that your original algorithm, as well as Tushar's answer, won't work if the original array contains repeated items. It won't match the behavior of the php function for this reason, either.

However, the following will work:

function array_diff(array1, array2) {
  return array1.filter(function(elm) {
    return array2.indexOf(elm) === -1;
  })
}

If needed, you can improve the performance (the above is O(n^2)) with a different algorithm that sorts the arrays first, but unless you're working with big arrays I prefer the simplicity of the above.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.