比较2个返回差异的数组

` `var array1 = [1, 2, 3, 4, 5, 6]; var array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]; var difference = []; jQuery.grep(array2, function(el) { if (jQuery.inArray(el, array1) == -1) difference.push(el); }); alert(" the difference is " + difference);​ // Changed variable name` `

` `var diff = \$(old_array).not(new_array).get();` `

`diff`现在包含`old_array`中不在`new_array`

` `_.difference(array1,array2)` `
` `var arrayDiff = function (firstArr, secondArr) { var i, o = [], fLen = firstArr.length, sLen = secondArr.length, len; if (fLen > sLen) { len = sLen; } else if (fLen < sLen) { len = fLen; } else { len = sLen; } for (i=0; i < len; i++) { if (firstArr[i] !== secondArr[i]) { o.push({idx: i, elem1: firstArr[i], elem2: secondArr[i]}); //idx: array index } } if (fLen > sLen) { // first > second for (i=sLen; i< fLen; i++) { o.push({idx: i, 0: firstArr[i], 1: undefined}); } } else if (fLen < sLen) { for (i=fLen; i< sLen; i++) { o.push({idx: i, 0: undefined, 1: secondArr[i]}); } } return o; };` `

` `Array.prototype.compareTo = function (array2){ var array1 = this; var difference = []; \$.grep(array2, function(el) { if (\$.inArray(el, array1) == -1) difference.push(el); }); if( difference.length === 0 ){ var \$i = 0; while(\$i < array1.length){ if(array1[\$i] !== array2[\$i]){ return false; } \$i++; } return true; } else { return false; } }` `

` `var arr1 = [1, 2, 3, 4, 5, 6,10], arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]; function array_diff(array1, array2){ var difference = \$.grep(array1, function(el) { return \$.inArray(el,array2) < 0}); return difference.concat(\$.grep(array2, function(el) { return \$.inArray(el,array1) < 0}));; } console.log(array_diff(arr1, arr2));` `
` `/** SUBTRACT ARRAYS **/ function subtractarrays(array1, array2){ var difference = []; for( var i = 0; i < array1.length; i++ ) { if( \$.inArray( array1[i], array2 ) == -1 ) { difference.push(array1[i]); } } return difference; }` `

` `var I_like = ["love", "sex", "food"]; var she_likes = ["love", "food"]; alert( "what I like and she does't like is: " + subtractarrays( I_like, she_likes ) ); //returns "Naughty"!` `

` `function arrayDiff(arr1, arr2) { var diff = {}; diff.arr1 = arr1.filter(function(value) { if (arr2.indexOf(value) === -1) { return value; } }); diff.arr2 = arr2.filter(function(value) { if (arr1.indexOf(value) === -1) { return value; } }); diff.concat = diff.arr1.concat(diff.arr2); return diff; }; var firstArray = [1,2,3,4]; var secondArray = [4,6,1,4]; console.log( arrayDiff(firstArray, secondArray) ); console.log( arrayDiff(firstArray, secondArray).arr1 ); // => [ 2, 3 ] console.log( arrayDiff(firstArray, secondArray).concat ); // => [ 2, 3, 6 ]` `

` `diff([1,2,3], [1,2,3,4,5]) // => [4,5]` `