let difference = arr1.filter(x => !arr2.includes(x));
(其他作者在这里)
我假设您正在比较一个普通数组。如果不是,您需要将进行循环更改为为…在循环。
function arr_diff (a1, a2) {
var a = [], diff = [];
for (var i = 0; i < a1.length; i++) {a[a1[i]] = true;}
for (var i = 0; i < a2.length; i++) {if (a[a2[i]]) {delete a[a2[i]];} else {a[a2[i]] = true;}}
for (var k in a) {diff.push(k);}
return diff;}
console.log(arr_diff(['a', 'b'], ['a', 'b', 'c', 'd']));console.log(arr_diff("abcd", "abcde"));console.log(arr_diff("zxc", "zxc"));
function diff(o, n) {// deal with empty listsif (o == undefined) o = [];if (n == undefined) n = [];
// sort both arrays (or this won't work)o.sort(); n.sort();
// don't compare if either list is emptyif (o.length == 0 || n.length == 0) return {added: n, removed: o};
// declare temporary variablesvar op = 0; var np = 0;var a = []; var r = [];
// compare arrays and add to add or remove listswhile (op < o.length && np < n.length) {if (o[op] < n[np]) {// push to diff?r.push(o[op]);op++;}else if (o[op] > n[np]) {// push to diff?a.push(n[np]);np++;}else {op++;np++;}}
// add remaining itemsif( np < n.length )a = a.concat(n.slice(np, n.length));if( op < o.length )r = r.concat(o.slice(op, o.length));
return {added: a, removed: r};}
function arr_diff(a1, a2){var a=[], diff=[];for(var i=0;i<a1.length;i++)a[a1[i]]=a1[i];for(var i=0;i<a2.length;i++)if(a[a2[i]]) delete a[a2[i]];else a[a2[i]]=a2[i];for(var k in a)diff.push(a[k]);return diff;}
[1,2,3].diff([1,2]); //Return ["3", "remove", "diff"] This is the wrong version
我的版本:
Array.prototype.diff = function(array2){var a = [],diff = [],array1 = this || [];
for (var i = 0; i < array1.length; i++) {a[array1[i]] = true;}for (var i = 0; i < array2.length; i++) {if (a[array2[i]]) {delete a[array2[i]];} else {a[array2[i]] = true;}}
for (var k in a) {if (!a.hasOwnProperty(k)){continue;}diff.push(k);}
return diff;}
if (!Array.prototype.diff) {Array.prototype.diff = function (array) {// if the other array is a falsy value, return a copy of this arrayif ((!array) || (!Array.prototype.isPrototypeOf(array))) {return this.slice(0);}
var diff = [];var original = this.slice(0);
for(var i=0; i < array.length; ++i) {var index = original.indexOf(array[i]);if (index > -1) {original.splice(index, 1);} else {diff.push(array[i]);}}
for (var i=0; i < original.length; ++i) {diff.push(original[i]);}return diff;}}
function arr_diff(a1, a2) {var a=[], diff=[];for(var i=0;i<a1.length;i++)a[a1[i]]=true;for(var i=0;i<a2.length;i++)if(a[a2[i].trim()]) delete a[a2[i].trim()];else a[a2[i].trim()]=true;for(var k in a)diff.push(k);return diff;}
If you are using Underscore.js, you can use the _.difference(a1, a2) function for case 1.
ES6 Set, for very large arrays
The code above works on all browsers. However, for large arrays of more than about 10,000 items, it becomes quite slow, because it has O(n²) complexity. On many modern browsers, we can take advantage of the ES6 Set object to speed things up. Lodash automatically uses Set when it's available. If you are not using lodash, use the following implementation, inspired by Axel Rauschmayer's blog post:
function difference(a1, a2) {var a2Set = new Set(a2);return a1.filter(function(x) { return !a2Set.has(x); });}
function symmetricDifference(a1, a2) {return difference(a1, a2).concat(difference(a2, a1));}
function diff(arr1, arr2) {var newArr = [];var arr = arr1.concat(arr2);
for (var i in arr){var f = arr[i];var t = 0;for (j=0; j<arr.length; j++){if(arr[j] === f){t++;}}if (t === 1){newArr.push(f);}}return newArr;}
var new_storage = JSON.parse('[{"id_order":"0003"},{"id_order":"0004"},{"id_order":"0006"}]');
var old_storage = JSON.parse('[{"id_order":"0001"},{"id_order":"0002"},{"id_order":"0003"},{"id_order":"0004"},{"id_order":"0005"}]');
let iterator = arrayA.values()let result = []for (entryA of iterator) {if (!arrayB.includes(entryA)) {result.push(entryA)} else {arrayB.splice(arrayB.indexOf(entryA), 1)}}
result.push(...arrayB)return result
var array_diff_naive = function(a,b){
var i, la = a.length, lb = b.length, res = [];
if (!la) return b; else if (!lb) return a;for (i = 0; i < la; i++) {if (b.indexOf(a[i]) === -1) res.push(a[i]);}for (i = 0; i < lb; i++) {if (a.indexOf(b[i]) === -1) res.push(b[i]);}return res;}
var array_diff_hash = function(a1,a2){
var a = [], diff = [];
for (var i = 0; i < a1.length; i++) {a[a1[i]] = true;}
for (var i = 0; i < a2.length; i++) {if (a[a2[i]]) {delete a[a2[i]];} else {a[a2[i]] = true;}}
for (var k in a) {diff.push(k);}
return diff;}
function difference(arr1, arr2){
let setA = new Set(arr1);let differenceSet = new Set(arr2.filter(ele => !setA.has(ele)));return [...differenceSet ];
}
/*** util function to calculate the difference between two arrays (pay attention to 'from' and 'to'),* it would return the mutations from 'from' to 'to'* @param { T[] } from* @param { T[] } to* @returns { { [x in string]: boolean } } it would return the stringified version of array element, true means added,* false means removed*/export function arrDiff<T>(from: T[], to: T[]): { [x in string]: boolean } {
var diff: { [x in string]: boolean } = {};var newItems: T[] = []diff = from.reduce((a, e) => ({ ...a, [JSON.stringify(e)]: true }), {})
for (var i = 0; i < to.length; i++) {if (diff[JSON.stringify(to[i])]) {delete diff[JSON.stringify(to[i])]} else {newItems.push(to[i])}}
return {...Object.keys(diff).reduce((a, e) => ({ ...a, [e]: false }), {}),...newItems.reduce((a, e) => ({ ...a, [JSON.stringify(e)]: true }), {})}}
function diffArray(arr1, arr2) {const newArr = [];
// arr1 match to arr2arr1.map((item)=>{if(arr2.indexOf(item)<0){console.log(item)newArr.push(item)}})
// arr2 match to arr1arr2.map((item)=>{if(arr1.indexOf(item)<0){newArr.push(item)}})
return newArr;}