-2

This is isn't really a question, it's a solution but I wanted to post it because I've seen it come up frequently. Feel free to suggest improvements though. I'll update my Fiddle with the results.

Using jQuery, this compares 2 arrays and outputs the differences in the two.

var array1 = [1, 2, 3, 4, 5, 6];
var array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var foo = [];
var i = 0;
jQuery.grep(array2, function(el) {
    if (jQuery.inArray(el, array1) == -1) foo.push(el);
    i++;
});
alert(" the difference is " + foo);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Difster
  • 3,264
  • 2
  • 22
  • 32
  • 3
    Put the problem in the question, and the solution in an answer. – Barmar Apr 15 '17 at 01:13
  • Use `console.log` instead of `alert`. – Barmar Apr 15 '17 at 01:15
  • You could use `.map()` instead of `grep()` – MrNew Apr 15 '17 at 01:16
  • When you use `grep`, the function should return a boolean that says whether to include the element in the result. Then you should assign the result to the array instead of using a global variable. – Barmar Apr 15 '17 at 01:17
  • 3
    I'm voting to close this question as off-topic because asking for comments on working code is more suited for CodeReview.stackexchange.com. – Barmar Apr 15 '17 at 01:18

1 Answers1

1

The library Underscore.js is very helpful for stuff like this.

http://underscorejs.org/#difference

_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]
Shivanshu Goyal
  • 1,374
  • 2
  • 16
  • 22