2
\$\begingroup\$

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

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

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);
});
\$\endgroup\$
1
  • \$\begingroup\$ Here is JSPerf Test(Not reliable) \$\endgroup\$
    – Tushar
    Nov 30, 2015 at 10:54
3
\$\begingroup\$

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.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ This should get more votes! \$\endgroup\$
    – argon
    Feb 15, 2021 at 7:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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