I have these two arrays: one is filled with information from an ajax request and another stores the buttons the user clicks on. I use this code (I filled with sample numbers):
我有这两个数组:一个包含来自ajax请求的信息,另一个存储用户单击的按钮。我使用这段代码(我填写了样本编号):
var array1 = [2, 4];
var array2 = [4, 2]; //It cames from the user button clicks, so it might be disordered.
array1.sort(); //Sorts both Ajax and user info.
array2.sort();
if (array1==array2) {
doSomething();
}else{
doAnotherThing();
}
But it always gives false
, even if the two arrays are the same, but with different name. (I checked this in Chrome's JS Console). So, is there any way I could know if these two arrays contain the same? Why is it giving false
? How can I know which values in the first array are not in the second?
但它总是给出false,即使这两个数组是相同的,但是名称不同。(我在Chrome的JS控制台检查了一下)。那么,我是否可以知道这两个数组是否包含相同的内容?为什么是假的?如何知道第一个数组中的哪些值不在第二个数组中?
10 个解决方案
#1
2
function arraysEqual(_arr1, _arr2) {
if (!Array.isArray(_arr1) || ! Array.isArray(_arr2) || _arr1.length !== _arr2.length)
return false;
var arr1 = _arr1.concat().sort();
var arr2 = _arr2.concat().sort();
for (var i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i])
return false;
}
return true;
}
Note that this doesn't modify original arrays unlike the accepted answer.
注意,这不会修改原始数组,不像所接受的答案。
#2
61
If your array items are not objects- if they are numbers or strings, for example, you can compare their joined strings to see if they have the same members in any order-
如果你的数组项目不是对象-如果它们是数字或字符串,例如,你可以比较它们的连接字符串,看看它们是否有相同的成员以任何顺序-
var array1= [10, 6, 19, 16, 14, 15, 2, 9, 5, 3, 4, 13, 8, 7, 1, 12, 18, 11, 20, 17];
var array2= [12, 18, 20, 11, 19, 14, 6, 7, 8, 16, 9, 3, 1, 13, 5, 4, 15, 10, 2, 17];
if(array1.sort().join(',')=== array2.sort().join(',')){
alert('same members');
}
else alert('not a match');
#3
39
Array.prototype.compare = function(testArr) {
if (this.length != testArr.length) return false;
for (var i = 0; i < testArr.length; i++) {
if (this[i].compare) { //To test values in nested arrays
if (!this[i].compare(testArr[i])) return false;
}
else if (this[i] !== testArr[i]) return false;
}
return true;
}
var array1 = [2, 4];
var array2 = [4, 2];
if(array1.sort().compare(array2.sort())) {
doSomething();
} else {
doAnotherThing();
}
Maybe?
也许?
#4
30
If you want to check only if two arrays have same values (regardless the number of occurrences and order of each value) you could do this by using lodash:
如果您只想检查两个数组是否具有相同的值(不管每个值出现的次数和顺序如何),可以使用lodash:
_.isEmpty(_.xor(array1, array2))
Short, simple and pretty!
短,简单而漂亮!
#5
23
Why your code didn't work
JavaScript has primitive data types and non-primitive data types.
JavaScript有原始数据类型和非原始数据类型。
For primitive data types, ==
and ===
check whether the things on either side of the bars have the same value. That's why 1 === 1
is true.
对于原始数据类型,==和===检查条两边的值是否相同。这就是为什么1 === 1是正确的。
For non-primitive data types like arrays, ==
and ===
check for reference equality. That is, they check whether arr1
and arr2
are the same object. In your example, the two arrays have the same objects in the same order, but are not equivalent.
对于非原始数据类型,如数组,=和===检查引用是否相等。也就是说,他们检查arr1和arr2是否相同。在您的示例中,这两个数组以相同的顺序拥有相同的对象,但并不相等。
Solutions
Two arrays, arr1
and arr2
, have the same members if and only if:
arr1和arr2这两个数组,当且仅当:
- Everything in
arr2
is inarr1
- arr2中的所有东西都在arr1中
AND
和
- Everything in
arr1
is inarr2
- arr1中的所有东西都在arr2中
So this will do the trick (ES2016):
所以这将是一个技巧(ES2016):
const containsAll = (arr1, arr2) =>
arr2.every(arr2Item => arr1.includes(arr2Item))
const sameMembers = (arr1, arr2) =>
containsAll(arr1, arr2) && containsAll(arr2, arr1);
sameMembers(arr1, arr2); // `true`
This second solution using Underscore is closer to what you were trying to do:
第二个使用下划线的解决方案更接近您所要做的:
arr1.sort();
arr2.sort();
_.isEqual(arr1, arr2); // `true`
It works because isEqual
checks for "deep equality," meaning it looks at more than just reference equality and compares values.
它之所以有效,是因为isEqual检查了“深度平等”,这意味着它不只是查看引用平等并比较值。
A solution to your third question
You also asked how to find out which things in arr1
are not contained in arr2
.
您还问了如何找出arr1中哪些东西不在arr2中。
This will do it (ES2015):
(ES2015):
const arr1 = [1, 2, 3, 4];
const arr2 = [3, 2, 1];
arr1.filter(arr1Item => !arr2.includes(arr1Item)); // `[4]`
You could also use Underscore's difference
: method:
你也可以使用下划线的差异:方法:
_.difference(arr1, arr2); // `[4]`
UPDATE
See @Redu's comment—my solution is for sameMembers
, but what you may have in mind is sameMembersInOrder
also-known-as deepEquals
.
参见@Redu的推荐——我的解决方案是针对sameMembers,但是您可能想到的是samembersinorder,也就是众所周知的deepEquals。
UPDATE 2
If you don't care about the order of the members of the arrays, ES2015+'s Set
may be a better data structure than Array
. See the MDN notes on how to implement isSuperset
and difference
using dangerous monkey-patching.
如果您不关心数组成员的顺序,ES2015+的集合可能是比数组更好的数据结构。参见MDN说明如何使用危险的monkey补丁实现问题集和差异。
#6
6
Object equality check:JSON.stringify(array1.sort()) === JSON.stringify(array2.sort())
对象相等检查:JSON.stringify(array1.sort()) == JSON.stringify(array2.sort())
The above test also works with arrays of objects in which case use a sort function as documented in http://www.w3schools.com/jsref/jsref_sort.asp
上面的测试也适用于对象数组,在这种情况下,使用一个排序函数,如http://www.w3schools.com/jsref/jsref_sort.asp。
Might suffice for small arrays with flat JSON schemas.
对于具有扁平JSON模式的小数组来说,这就足够了。
#7
3
When you compare those two arrays, you're comparing the objects that represent the arrays, not the contents.
当您比较这两个数组时,您是在比较表示数组的对象,而不是内容。
You'll have to use a function to compare the two. You could write your own that simply loops though one and compares it to the other after you check that the lengths are the same.
你必须用一个函数来比较两者。您可以编写自己的那个简单的循环遍历其中一个,并在检查长度是否相同后将其与另一个进行比较。
#8
1
If you are using the Prototype Framework, you can use the intersect method of an array to find out of they are the same (regardless of the order):
如果您使用的是原型框架,您可以使用数组的intersect方法来查找它们是否相同(无论顺序如何):
var array1 = [1,2];
var array2 = [2,1];
if(array1.intersect(array2).length === array1.length) {
alert("arrays are the same!");
}
#9
1
I had simple integer values in a Game project
Had less number of values in each array, also, needed that original array untouched
So, I did the below, it worked fine. (Code edited to paste here)
我有一个简单的整数值,在一个游戏项目中,每个数组中值的数量更少,而且,需要原始数组不受影响,所以,我做了下面的操作,效果很好。(代码被编辑为粘贴到这里)
var sourceArray = [1, 2, 3];
var targetArray = [3, 2, 1];
if (sourceArray.length !== targetArray.length) {
// not equal
// did something
return false;
}
var newSortedSourceArray = sourceArray.slice().sort();
var newSortedTargetArray = targetArray.slice().sort();
if (newSortedSourceArray.toString() !== newSortedTargetArray.toString()) { // MAIN CHECK
// not equal
// did something
return false;
}
else {
// equal
// did something
// continued further below
}
// did some more work
return true;
Hope that helps.
希望有帮助。
#10
0
kindly check this answer
请检查这个答案
var arr1= [12,18];
var arr2= [12, 18, 20, 11, 19, 14, 6, 7, 8, 16, 9, 3, 1, 13, 5, 4, 15, 10, 2, 17];
for(i=0;i<arr1.length;i++)
{
var array1=arr1[i];
for(j=0;j<arr2.length;j++)
{
var array2=arr2[j];
if(array1==array2)
{
return true;
}
}
}
#1
2
function arraysEqual(_arr1, _arr2) {
if (!Array.isArray(_arr1) || ! Array.isArray(_arr2) || _arr1.length !== _arr2.length)
return false;
var arr1 = _arr1.concat().sort();
var arr2 = _arr2.concat().sort();
for (var i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i])
return false;
}
return true;
}
Note that this doesn't modify original arrays unlike the accepted answer.
注意,这不会修改原始数组,不像所接受的答案。
#2
61
If your array items are not objects- if they are numbers or strings, for example, you can compare their joined strings to see if they have the same members in any order-
如果你的数组项目不是对象-如果它们是数字或字符串,例如,你可以比较它们的连接字符串,看看它们是否有相同的成员以任何顺序-
var array1= [10, 6, 19, 16, 14, 15, 2, 9, 5, 3, 4, 13, 8, 7, 1, 12, 18, 11, 20, 17];
var array2= [12, 18, 20, 11, 19, 14, 6, 7, 8, 16, 9, 3, 1, 13, 5, 4, 15, 10, 2, 17];
if(array1.sort().join(',')=== array2.sort().join(',')){
alert('same members');
}
else alert('not a match');
#3
39
Array.prototype.compare = function(testArr) {
if (this.length != testArr.length) return false;
for (var i = 0; i < testArr.length; i++) {
if (this[i].compare) { //To test values in nested arrays
if (!this[i].compare(testArr[i])) return false;
}
else if (this[i] !== testArr[i]) return false;
}
return true;
}
var array1 = [2, 4];
var array2 = [4, 2];
if(array1.sort().compare(array2.sort())) {
doSomething();
} else {
doAnotherThing();
}
Maybe?
也许?
#4
30
If you want to check only if two arrays have same values (regardless the number of occurrences and order of each value) you could do this by using lodash:
如果您只想检查两个数组是否具有相同的值(不管每个值出现的次数和顺序如何),可以使用lodash:
_.isEmpty(_.xor(array1, array2))
Short, simple and pretty!
短,简单而漂亮!
#5
23
Why your code didn't work
JavaScript has primitive data types and non-primitive data types.
JavaScript有原始数据类型和非原始数据类型。
For primitive data types, ==
and ===
check whether the things on either side of the bars have the same value. That's why 1 === 1
is true.
对于原始数据类型,==和===检查条两边的值是否相同。这就是为什么1 === 1是正确的。
For non-primitive data types like arrays, ==
and ===
check for reference equality. That is, they check whether arr1
and arr2
are the same object. In your example, the two arrays have the same objects in the same order, but are not equivalent.
对于非原始数据类型,如数组,=和===检查引用是否相等。也就是说,他们检查arr1和arr2是否相同。在您的示例中,这两个数组以相同的顺序拥有相同的对象,但并不相等。
Solutions
Two arrays, arr1
and arr2
, have the same members if and only if:
arr1和arr2这两个数组,当且仅当:
- Everything in
arr2
is inarr1
- arr2中的所有东西都在arr1中
AND
和
- Everything in
arr1
is inarr2
- arr1中的所有东西都在arr2中
So this will do the trick (ES2016):
所以这将是一个技巧(ES2016):
const containsAll = (arr1, arr2) =>
arr2.every(arr2Item => arr1.includes(arr2Item))
const sameMembers = (arr1, arr2) =>
containsAll(arr1, arr2) && containsAll(arr2, arr1);
sameMembers(arr1, arr2); // `true`
This second solution using Underscore is closer to what you were trying to do:
第二个使用下划线的解决方案更接近您所要做的:
arr1.sort();
arr2.sort();
_.isEqual(arr1, arr2); // `true`
It works because isEqual
checks for "deep equality," meaning it looks at more than just reference equality and compares values.
它之所以有效,是因为isEqual检查了“深度平等”,这意味着它不只是查看引用平等并比较值。
A solution to your third question
You also asked how to find out which things in arr1
are not contained in arr2
.
您还问了如何找出arr1中哪些东西不在arr2中。
This will do it (ES2015):
(ES2015):
const arr1 = [1, 2, 3, 4];
const arr2 = [3, 2, 1];
arr1.filter(arr1Item => !arr2.includes(arr1Item)); // `[4]`
You could also use Underscore's difference
: method:
你也可以使用下划线的差异:方法:
_.difference(arr1, arr2); // `[4]`
UPDATE
See @Redu's comment—my solution is for sameMembers
, but what you may have in mind is sameMembersInOrder
also-known-as deepEquals
.
参见@Redu的推荐——我的解决方案是针对sameMembers,但是您可能想到的是samembersinorder,也就是众所周知的deepEquals。
UPDATE 2
If you don't care about the order of the members of the arrays, ES2015+'s Set
may be a better data structure than Array
. See the MDN notes on how to implement isSuperset
and difference
using dangerous monkey-patching.
如果您不关心数组成员的顺序,ES2015+的集合可能是比数组更好的数据结构。参见MDN说明如何使用危险的monkey补丁实现问题集和差异。
#6
6
Object equality check:JSON.stringify(array1.sort()) === JSON.stringify(array2.sort())
对象相等检查:JSON.stringify(array1.sort()) == JSON.stringify(array2.sort())
The above test also works with arrays of objects in which case use a sort function as documented in http://www.w3schools.com/jsref/jsref_sort.asp
上面的测试也适用于对象数组,在这种情况下,使用一个排序函数,如http://www.w3schools.com/jsref/jsref_sort.asp。
Might suffice for small arrays with flat JSON schemas.
对于具有扁平JSON模式的小数组来说,这就足够了。
#7
3
When you compare those two arrays, you're comparing the objects that represent the arrays, not the contents.
当您比较这两个数组时,您是在比较表示数组的对象,而不是内容。
You'll have to use a function to compare the two. You could write your own that simply loops though one and compares it to the other after you check that the lengths are the same.
你必须用一个函数来比较两者。您可以编写自己的那个简单的循环遍历其中一个,并在检查长度是否相同后将其与另一个进行比较。
#8
1
If you are using the Prototype Framework, you can use the intersect method of an array to find out of they are the same (regardless of the order):
如果您使用的是原型框架,您可以使用数组的intersect方法来查找它们是否相同(无论顺序如何):
var array1 = [1,2];
var array2 = [2,1];
if(array1.intersect(array2).length === array1.length) {
alert("arrays are the same!");
}
#9
1
I had simple integer values in a Game project
Had less number of values in each array, also, needed that original array untouched
So, I did the below, it worked fine. (Code edited to paste here)
我有一个简单的整数值,在一个游戏项目中,每个数组中值的数量更少,而且,需要原始数组不受影响,所以,我做了下面的操作,效果很好。(代码被编辑为粘贴到这里)
var sourceArray = [1, 2, 3];
var targetArray = [3, 2, 1];
if (sourceArray.length !== targetArray.length) {
// not equal
// did something
return false;
}
var newSortedSourceArray = sourceArray.slice().sort();
var newSortedTargetArray = targetArray.slice().sort();
if (newSortedSourceArray.toString() !== newSortedTargetArray.toString()) { // MAIN CHECK
// not equal
// did something
return false;
}
else {
// equal
// did something
// continued further below
}
// did some more work
return true;
Hope that helps.
希望有帮助。
#10
0
kindly check this answer
请检查这个答案
var arr1= [12,18];
var arr2= [12, 18, 20, 11, 19, 14, 6, 7, 8, 16, 9, 3, 1, 13, 5, 4, 15, 10, 2, 17];
for(i=0;i<arr1.length;i++)
{
var array1=arr1[i];
for(j=0;j<arr2.length;j++)
{
var array2=arr2[j];
if(array1==array2)
{
return true;
}
}
}