如何在JavaScript中获得两个数组之间的差异?
有没有办法返回JavaScript中两个数组之间的差异 例如:如何在JavaScript中获得两个数组之间的差异?,javascript,arrays,array-difference,Javascript,Arrays,Array Difference,有没有办法返回JavaScript中两个数组之间的差异 例如: var a1=['a','b']; 变量a2=['a','b','c','d']; //需要[“c”、“d”] 在这种情况下,您可以使用。它针对这种操作(并集、交集、差分)进行了优化 确保它适用于您的案例,一旦它不允许重复 var a = new JS.Set([1,2,3,4,5,6,7,8,9]); var b = new JS.Set([2,4,6,8]); a.difference(b) // -> Set{1,3,
var a1=['a','b'];
变量a2=['a','b','c','d'];
//需要[“c”、“d”]
在这种情况下,您可以使用。它针对这种操作(并集、交集、差分)进行了优化
确保它适用于您的案例,一旦它不允许重复
var a = new JS.Set([1,2,3,4,5,6,7,8,9]);
var b = new JS.Set([2,4,6,8]);
a.difference(b)
// -> Set{1,3,5,7,9}
我假设您正在比较一个普通数组。如果不是,则需要将for循环更改为for。。循环中
函数arr_diff(a1、a2){
变量a=[],差异=[];
对于(变量i=0;i这个怎么样:
Array.prototype.contains = function(needle){
for (var i=0; i<this.length; i++)
if (this[i] == needle) return true;
return false;
}
Array.prototype.diff = function(compare) {
return this.filter(function(elem) {return !compare.contains(elem);})
}
var a = new Array(1,4,7, 9);
var b = new Array(4, 8, 7);
alert(a.diff(b));
Array.prototype.contains=函数(指针){
对于(var i=0;i我想要一个类似的函数,它接受一个旧数组和一个新数组,并给我一个添加项数组和一个删除项数组,我希望它是有效的(所以不包含!)
您可以在此处使用我建议的解决方案:
有人能看到该算法的任何问题/改进吗?谢谢
代码列表:
function diff(o, n) {
// deal with empty lists
if (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 empty
if (o.length == 0 || n.length == 0) return {added: n, removed: o};
// declare temporary variables
var op = 0; var np = 0;
var a = []; var r = [];
// compare arrays and add to add or remove lists
while (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 items
if( 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};
}
函数差(o,n){
//处理空名单
如果(o==未定义)o=[];
如果(n==未定义)n=[];
//对两个数组进行排序(否则这将不起作用)
o、 排序;
//如果任一列表为空,则不进行比较
if(o.length==0 | | n.length==0)返回{added:n,removed:o};
//声明临时变量
var op=0;var np=0;
var a=[];var=[];
//比较数组并添加以添加或删除列表
while(opn[np]){
//推动差异化?
a、 push(n[np]);
np++;
}
否则{
op++;np++;
}
}
//添加剩余项目
if(np
Array.prototype.diff=函数(a){
返回this.filter(函数(i){返回a.indexOf(i)<0;});
};
//////////////
//例子//
//////////////
常数dif1=[1,2,3,4,5,6].diff([3,4,5]);
console.log(dif1);//=>[1,2,6]
const dif2=[“test1”、“test2”、“test3”、“test4”、“test5”、“test6”].diff([“test1”、“test2”、“test3”、“test4”);
console.log(dif2);//=>[“test5”、“test6”]
使用您可以:
要从一个数组中减去另一个数组,只需使用以下代码段:
var a1 = ['1','2','3','4','6'];
var a2 = ['3','4','5'];
var items = new Array();
items = jQuery.grep(a1,function (item) {
return jQuery.inArray(item, a2) < 0;
});
vara1=['1','2','3','4','6'];
变量a2=['3','4','5'];
var items=新数组();
items=jQuery.grep(a1,函数(item){
返回jQuery.inArray(item,a2)<0;
});
它将返回['1','2','6'],这些是第一个数组中的项,而第二个数组中不存在这些项
因此,根据您的问题示例,以下代码是精确的解决方案:
var array1 = ["test1", "test2","test3", "test4"];
var array2 = ["test1", "test2","test3","test4", "test5", "test6"];
var _array = new Array();
_array = jQuery.grep(array2, function (item) {
return jQuery.inArray(item, array1) < 0;
});
var array1=[“test1”、“test2”、“test3”、“test4”];
var array2=[“test1”、“test2”、“test3”、“test4”、“test5”、“test6”];
var_数组=新数组();
_array=jQuery.grep(array2,函数(项){
返回jQuery.inArray(item,array1)<0;
});
使用indexOf()
的解决方案适用于小型阵列,但随着长度的增加,算法的性能接近于O(n^2)
。这里有一个解决方案,它将对象用作关联数组,将数组条目存储为键,从而对非常大的数组执行得更好;它还自动消除重复条目,但仅适用于字符串值(或可以安全存储为字符串的值):
函数arrayDiff(a1,a2){
VarO1={},o2={},diff=[],i,len,k;
对于(i=0,len=a1.length;i['c','d']
(或其替代品)也可以做到这一点:
(R)eturns the values from array that are not present in the other arrays
_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]
与任何下划线函数一样,您也可以在更面向对象的样式中使用它:
_([1, 2, 3, 4, 5]).difference([5, 2, 10]);
Joshaven Potter的上述回答很好。但它返回数组B中不在数组C中的元素,但不是相反的方式。例如,如果var a=[1,2,3,4,5,6].diff([3,4,5,7]);
则它将输出:==>[1,2,6]
,但不是[1,2,6,7]
,这是两者之间的实际差异。您仍然可以使用上面的波特代码,但也可以向后重新进行比较:
Array.prototype.diff = function(a) {
return this.filter(function(i) {return !(a.indexOf(i) > -1);});
};
////////////////////
// Examples
////////////////////
var a=[1,2,3,4,5,6].diff( [3,4,5,7]);
var b=[3,4,5,7].diff([1,2,3,4,5,6]);
var c=a.concat(b);
console.log(c);
这应该会输出:[1,2,6,7]
您可以使用下划线.js:
您需要用于阵列的方法:
_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]
_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2]
这是使用jQuery获得您想要的结果的最简单方法:
var diff = $(old_array).not(new_array).get();
diff
现在包含old\u array
中不在new\u array中的内容
纯JavaScript解决方案(无库)
与旧浏览器兼容(不使用过滤器
)
O(n^2)
可选的fn
回调参数,用于指定如何比较数组项
功能差异(a、b、fn){
var max=数学最大值(a.长度,b.长度);
d=[];
fn=typeof fn==“函数”?fn:false
对于(变量i=0;ivar diff = $(old_array).not(new_array).get();
var a = ['a', 'b', 'c', 'd'];
var b = ['a', 'b'];
var b1 = new Set(b);
var difference = [...new Set(a.filter(x => !b1.has(x)))];
var a1 = ['a', 'b' ];
var a2 = [ 'b', 'c'];
function difference(a1, a2) {
var result = [];
for (var i = 0; i < a1.length; i++) {
if (a2.indexOf(a1[i]) === -1) {
result.push(a1[i]);
}
}
return result;
}
function symmetricDifference(a1, a2) {
var result = [];
for (var i = 0; i < a1.length; i++) {
if (a2.indexOf(a1[i]) === -1) {
result.push(a1[i]);
}
}
for (i = 0; i < a2.length; i++) {
if (a1.indexOf(a2[i]) === -1) {
result.push(a2[i]);
}
}
return result;
}
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(a1, a2) {
return a1.concat(a2).filter(function(val, index, arr){
return arr.indexOf(val) === arr.lastIndexOf(val);
});
}
Array.prototype.difference = function(e) {
return this.filter(function(i) {return e.indexOf(i) < 0;});
};
eg:-
[1,2,3,4,5,6,7].difference( [3,4,5] );
=> [1, 2, 6 , 7]
let intersection = arr1.filter(x => arr2.includes(x));
let difference = arr1.filter(x => !arr2.includes(x));
let difference = arr1
.filter(x => !arr2.includes(x))
.concat(arr2.filter(x => !arr1.includes(x)));
Array.prototype.diff = function(arr2) { return this.filter(x => !arr2.includes(x)); }
[1, 2, 3].diff([2, 3])
function diffArray(arr1, arr2) {
var newArr = arr1.concat(arr2);
return newArr.filter(function(i){
return newArr.indexOf(i) == newArr.lastIndexOf(i);
});
}
[+left difference] [-intersection] [-right difference]
[-left difference] [-intersection] [+right difference]
[+left difference] [-intersection] [+right difference]
function diffArray(arr1, arr2) {
return arr1.concat(arr2).filter(function (val) {
if (!(arr1.includes(val) && arr2.includes(val)))
return val;
});
}
diffArray([1, 2, 3, 7], [3, 2, 1, 4, 5]); // return [7, 4, 5]
const diffArray = (arr1, arr2) => arr1.concat(arr2)
.filter(val => !(arr1.includes(val) && arr2.includes(val)));
diffArray([1, 2, 3, 7], [3, 2, 1, 4, 5]); // return [7, 4, 5]
function diff(a, b) {
var u = a.slice(); //dup the array
b.map(e => {
if (u.indexOf(e) > -1) delete u[u.indexOf(e)]
else u.push(e) //add non existing item to temp array
})
return u.filter((x) => {return (x != null)}) //flatten result
}
function arrDiff(arr1, arr2) {
var arrays = [arr1, arr2].sort((a, b) => a.length - b.length);
var smallSet = new Set(arrays[0]);
return arrays[1].filter(x => !smallSet.has(x));
}
// diff between just two arrays:
function arrayDiff(a, b) {
return [
...a.filter(x => !b.includes(x)),
...b.filter(x => !a.includes(x))
];
}
// diff between multiple arrays:
function arrayDiff(...arrays) {
return [].concat(...arrays.map( (arr, i) => {
const others = arrays.slice(0);
others.splice(i, 1);
const unique = [...new Set([].concat(...others))];
return arr.filter(x => !unique.includes(x));
}));
}
// diff between just two arrays:
function arrayDiff(a, b) {
return [
...a.filter(x => b.indexOf(x) === -1),
...b.filter(x => a.indexOf(x) === -1)
];
}
// diff between multiple arrays:
function arrayDiff(...arrays) {
return [].concat(...arrays.map( (arr, i) => {
const others = arrays.slice(0);
others.splice(i, 1);
const unique = [...new Set([].concat(...others))];
return arr.filter(x => unique.indexOf(x) === -1);
}));
}
// diff between just two arrays:
function arrayDiff(a, b) {
var arrays = Array.prototype.slice.call(arguments);
var diff = [];
arrays.forEach(function(arr, i) {
var other = i === 1 ? a : b;
arr.forEach(function(x) {
if (other.indexOf(x) === -1) {
diff.push(x);
}
});
})
return diff;
}
// diff between multiple arrays:
function arrayDiff() {
var arrays = Array.prototype.slice.call(arguments);
var diff = [];
arrays.forEach(function(arr, i) {
var others = arrays.slice(0);
others.splice(i, 1);
var otherValues = Array.prototype.concat.apply([], others);
var unique = otherValues.filter(function (x, j) {
return otherValues.indexOf(x) === j;
});
diff = diff.concat(arr.filter(x => unique.indexOf(x) === -1));
});
return diff;
}
// diff between two arrays:
const a = ['a', 'd', 'e'];
const b = ['a', 'b', 'c', 'd'];
arrayDiff(a, b); // (3) ["e", "b", "c"]
// diff between multiple arrays
const a = ['b', 'c', 'd', 'e', 'g'];
const b = ['a', 'b'];
const c = ['a', 'e', 'f'];
arrayDiff(a, b, c); // (4) ["c", "d", "g", "f"]
function arrayDiffByKey(key, ...arrays) {
return [].concat(...arrays.map( (arr, i) => {
const others = arrays.slice(0);
others.splice(i, 1);
const unique = [...new Set([].concat(...others))];
return arr.filter( x =>
!unique.some(y => x[key] === y[key])
);
}));
}
const a = [{k:1}, {k:2}, {k:3}];
const b = [{k:1}, {k:4}, {k:5}, {k:6}];
const c = [{k:3}, {k:5}, {k:7}];
arrayDiffByKey('k', a, b, c); // (4) [{k:2}, {k:4}, {k:6}, {k:7}]
var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];
a2.filter(d => !a1.includes(d)) // gives ["c", "d"]
a2.filter(d => a1.includes(d)) // gives ["a", "b"]
[ ...a2.filter(d => !a1.includes(d)),
...a1.filter(d => !a2.includes(d)) ]
function getDiff(arr1,arr2){
let k = {};
let diff = []
arr1.map(i=>{
if (!k.hasOwnProperty(i)) {
k[i] = 1
}
}
)
arr2.map(j=>{
if (!k.hasOwnProperty(j)) {
k[j] = 1;
} else {
k[j] = 2;
}
}
)
for (var i in k) {
if (k[i] === 1)
diff.push(+i)
}
return diff
}
getDiff([4, 3, 52, 3, 5, 67, 9, 3],[4, 5, 6, 75, 3, 334, 5, 5, 6])
function difference(arr1, arr2){
let setA = new Set(arr1);
let differenceSet = new Set(arr2.filter(ele => !setA.has(ele)));
return [...differenceSet ];
}
function absDifference(arr1, arr2){
const {larger, smaller} = arr1.length > arr2.length ?
{larger: arr1, smaller: arr2} : {larger: arr2, smaller: arr1}
let setA = new Set(smaller);
let absDifferenceSet = new Set(larger.filter(ele => !setA.has(ele)));
return [...absDifferenceSet ];
}