How to know if two arrays have the same values
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):
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?
javascript arrays compare
add a comment |
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):
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?
javascript arrays compare
1
I am pretty certain you need to go through each element of the arrays.
– Thomas Li
Jun 3 '11 at 15:35
Do you know why it returns false? Curious.
– RobW
Jun 1 '14 at 19:50
See @Andrew 's answer stackoverflow.com/a/6229263/702565
– Carlos Precioso
Jun 3 '14 at 22:32
possible duplicate of how to check javascript array equals?
– Palec
Jun 24 '14 at 14:41
add a comment |
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):
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?
javascript arrays compare
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):
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?
javascript arrays compare
javascript arrays compare
edited Mar 7 '16 at 16:27
alex
338k166765911
338k166765911
asked Jun 3 '11 at 15:32
Carlos Precioso
1,08611124
1,08611124
1
I am pretty certain you need to go through each element of the arrays.
– Thomas Li
Jun 3 '11 at 15:35
Do you know why it returns false? Curious.
– RobW
Jun 1 '14 at 19:50
See @Andrew 's answer stackoverflow.com/a/6229263/702565
– Carlos Precioso
Jun 3 '14 at 22:32
possible duplicate of how to check javascript array equals?
– Palec
Jun 24 '14 at 14:41
add a comment |
1
I am pretty certain you need to go through each element of the arrays.
– Thomas Li
Jun 3 '11 at 15:35
Do you know why it returns false? Curious.
– RobW
Jun 1 '14 at 19:50
See @Andrew 's answer stackoverflow.com/a/6229263/702565
– Carlos Precioso
Jun 3 '14 at 22:32
possible duplicate of how to check javascript array equals?
– Palec
Jun 24 '14 at 14:41
1
1
I am pretty certain you need to go through each element of the arrays.
– Thomas Li
Jun 3 '11 at 15:35
I am pretty certain you need to go through each element of the arrays.
– Thomas Li
Jun 3 '11 at 15:35
Do you know why it returns false? Curious.
– RobW
Jun 1 '14 at 19:50
Do you know why it returns false? Curious.
– RobW
Jun 1 '14 at 19:50
See @Andrew 's answer stackoverflow.com/a/6229263/702565
– Carlos Precioso
Jun 3 '14 at 22:32
See @Andrew 's answer stackoverflow.com/a/6229263/702565
– Carlos Precioso
Jun 3 '14 at 22:32
possible duplicate of how to check javascript array equals?
– Palec
Jun 24 '14 at 14:41
possible duplicate of how to check javascript array equals?
– Palec
Jun 24 '14 at 14:41
add a comment |
11 Answers
11
active
oldest
votes
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 a previous answer.
add a comment |
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');
This will work well for primitives or objects that have uniquely identifying toString values, but not for just any objects.
– devios1
Jan 26 '12 at 15:59
Thanks! neat solution
– Gaston Sanchez
Jul 13 '13 at 20:57
2
Beware of null items and sorting. I ended up in my case with strings to compare like ",2,2,3" and "2,2,3," which of course aren't strictly equal.
– barbara.post
Jul 30 '15 at 12:25
1
Could fail for strings, i.e.['a', 'b']
and['a,b']
. I would only recommend this technique for small throwaway scripts.
– alex
Mar 7 '16 at 16:23
Hi kennebec, can you tell how to save matched into another array
– Vinoth
Aug 8 '17 at 7:15
|
show 2 more comments
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?
Thank you! It works just as desired. I modified a little the function so I could also know how many mismatches are.
– Carlos Precioso
Jun 3 '11 at 15:43
false for [2,4] [4,2].
– Suraz Khanal
Dec 17 '16 at 7:43
@SurazKhanal Still need to sort
– Aaron McMillin
Mar 15 '17 at 15:13
add a comment |
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:
_.isEmpty(_.xor(array1, array2))
Short, simple and pretty!
1
I cannot seem to findxor
in the underscore docs? Are you thinking of IODash?
– Patrick Mencias-lewis
Nov 9 '15 at 18:12
You are right. Edited my response. Thanks Patrick.
– Technotronic
Nov 22 '15 at 9:20
add a comment |
Why your code didn't work
JavaScript has primitive data types and non-primitive data types.
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.
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.
Solutions
Two arrays, arr1
and arr2
, have the same members if and only if:
- Everything in
arr2
is inarr1
AND
- Everything in
arr1
is inarr2
So this will do the trick (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.
A solution to your third question
You also asked how to find out which things in arr1
are not contained in arr2
.
This will do it (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
.
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.
Your solutions are wrong. "Two arrays, arr1 and arr2, have the same members if and only if: Everything in arr2 is in arr1 AND Everything in arr1 is in arr2" this is also wrong. This is an array not a set. SosameMembers([1,1,2],[2,1,2]);
should return false.
– Redu
Aug 26 '16 at 8:27
@Redu guess it depends on what "same members" means—I take it to mean "has the same members."sameMembers([1,1,2],[2,1,2])
should returntrue
, in my opinion.sameMembersInOrder([1,1,2],[2,1,2])
AKAdeepEquals([1,1,2],[2,1,2])
should returnfalse
.
– Max Heiber
Aug 26 '16 at 15:40
add a comment |
Object equality check: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
Might suffice for small arrays with flat JSON schemas.
add a comment |
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.
add a comment |
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):
var array1 = [1,2];
var array2 = [2,1];
if(array1.intersect(array2).length === array1.length) {
alert("arrays are the same!");
}
This doesn't work -[1,2].intersect([1,2,3]).length === [1,2].length
returns true. You should compare the length of the original arrays too, I've edited the post to demonstrate.
– GMA
Feb 24 '14 at 3:12
Actually I've just realised my suggested edit doesn't work in the case of duplicates... e.g. it will return false forarray1 = [1,1,2]; array2 = [1,1,2];
... the original answer doesn't fail for that input.
– GMA
Feb 24 '14 at 4:13
ah yes, you're right..
– Erfan
Feb 24 '14 at 9:31
You can do the opposite with_.difference(array1, array2).length;
– Vic
Sep 4 '15 at 20:05
add a comment |
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.
add a comment |
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
This is functionally equivalent to this answer, save for a couple of errors. First, this should all be wrapped within a function, or thereturn
will have no effect. Second, you should check the sorted arrays, as[1,2]
and[2,1]
will be detected as not the same. Third and most important, this will actually only check if some element is the same. The conditional should beif (array1!==array2) {return false;}
. Maybe this can help you in the future!
– Carlos Precioso
May 3 '18 at 17:10
And as an extra comment, do try to use indentation for better understanding of the code flow, as well as clearer variable names. E.g.:array1
andarray2
could be renamedelem1
andelem2
. Both these tips will save you plenty of headaches in the future!
– Carlos Precioso
May 3 '18 at 17:17
1
On further inspection, why the double loop? Both arrays should be the same length, and if not, they are directly not equal. This way you can use only one loop. Right now, this code checks if any of the elements of the first array are anywhere in the second one. Check this answer to see how you should implement it. Good luck in your JavaScript journey!
– Carlos Precioso
May 3 '18 at 17:23
add a comment |
Using ES6
We'll use Ramda's equals
function, but instead we can use Lodash's or Underscore's isEqual
:
const R = require('ramda');
const arraysHaveSameValues = (arr1, arr2) => R.equals( [...arr1].sort(), [...arr2].sort() )
Using the spread opporator, we avoid mutating the original arrays, and we keep our function pure.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f6229197%2fhow-to-know-if-two-arrays-have-the-same-values%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
11 Answers
11
active
oldest
votes
11 Answers
11
active
oldest
votes
active
oldest
votes
active
oldest
votes
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 a previous answer.
add a comment |
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 a previous answer.
add a comment |
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 a previous answer.
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 a previous answer.
edited Dec 27 '18 at 14:48
Eric Brandt
2,2471524
2,2471524
answered Apr 18 '17 at 17:17
Maciej Krawczyk
4,84831329
4,84831329
add a comment |
add a comment |
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');
This will work well for primitives or objects that have uniquely identifying toString values, but not for just any objects.
– devios1
Jan 26 '12 at 15:59
Thanks! neat solution
– Gaston Sanchez
Jul 13 '13 at 20:57
2
Beware of null items and sorting. I ended up in my case with strings to compare like ",2,2,3" and "2,2,3," which of course aren't strictly equal.
– barbara.post
Jul 30 '15 at 12:25
1
Could fail for strings, i.e.['a', 'b']
and['a,b']
. I would only recommend this technique for small throwaway scripts.
– alex
Mar 7 '16 at 16:23
Hi kennebec, can you tell how to save matched into another array
– Vinoth
Aug 8 '17 at 7:15
|
show 2 more comments
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');
This will work well for primitives or objects that have uniquely identifying toString values, but not for just any objects.
– devios1
Jan 26 '12 at 15:59
Thanks! neat solution
– Gaston Sanchez
Jul 13 '13 at 20:57
2
Beware of null items and sorting. I ended up in my case with strings to compare like ",2,2,3" and "2,2,3," which of course aren't strictly equal.
– barbara.post
Jul 30 '15 at 12:25
1
Could fail for strings, i.e.['a', 'b']
and['a,b']
. I would only recommend this technique for small throwaway scripts.
– alex
Mar 7 '16 at 16:23
Hi kennebec, can you tell how to save matched into another array
– Vinoth
Aug 8 '17 at 7:15
|
show 2 more comments
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');
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');
answered Jun 3 '11 at 17:06
kennebec
78k1986115
78k1986115
This will work well for primitives or objects that have uniquely identifying toString values, but not for just any objects.
– devios1
Jan 26 '12 at 15:59
Thanks! neat solution
– Gaston Sanchez
Jul 13 '13 at 20:57
2
Beware of null items and sorting. I ended up in my case with strings to compare like ",2,2,3" and "2,2,3," which of course aren't strictly equal.
– barbara.post
Jul 30 '15 at 12:25
1
Could fail for strings, i.e.['a', 'b']
and['a,b']
. I would only recommend this technique for small throwaway scripts.
– alex
Mar 7 '16 at 16:23
Hi kennebec, can you tell how to save matched into another array
– Vinoth
Aug 8 '17 at 7:15
|
show 2 more comments
This will work well for primitives or objects that have uniquely identifying toString values, but not for just any objects.
– devios1
Jan 26 '12 at 15:59
Thanks! neat solution
– Gaston Sanchez
Jul 13 '13 at 20:57
2
Beware of null items and sorting. I ended up in my case with strings to compare like ",2,2,3" and "2,2,3," which of course aren't strictly equal.
– barbara.post
Jul 30 '15 at 12:25
1
Could fail for strings, i.e.['a', 'b']
and['a,b']
. I would only recommend this technique for small throwaway scripts.
– alex
Mar 7 '16 at 16:23
Hi kennebec, can you tell how to save matched into another array
– Vinoth
Aug 8 '17 at 7:15
This will work well for primitives or objects that have uniquely identifying toString values, but not for just any objects.
– devios1
Jan 26 '12 at 15:59
This will work well for primitives or objects that have uniquely identifying toString values, but not for just any objects.
– devios1
Jan 26 '12 at 15:59
Thanks! neat solution
– Gaston Sanchez
Jul 13 '13 at 20:57
Thanks! neat solution
– Gaston Sanchez
Jul 13 '13 at 20:57
2
2
Beware of null items and sorting. I ended up in my case with strings to compare like ",2,2,3" and "2,2,3," which of course aren't strictly equal.
– barbara.post
Jul 30 '15 at 12:25
Beware of null items and sorting. I ended up in my case with strings to compare like ",2,2,3" and "2,2,3," which of course aren't strictly equal.
– barbara.post
Jul 30 '15 at 12:25
1
1
Could fail for strings, i.e.
['a', 'b']
and ['a,b']
. I would only recommend this technique for small throwaway scripts.– alex
Mar 7 '16 at 16:23
Could fail for strings, i.e.
['a', 'b']
and ['a,b']
. I would only recommend this technique for small throwaway scripts.– alex
Mar 7 '16 at 16:23
Hi kennebec, can you tell how to save matched into another array
– Vinoth
Aug 8 '17 at 7:15
Hi kennebec, can you tell how to save matched into another array
– Vinoth
Aug 8 '17 at 7:15
|
show 2 more comments
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?
Thank you! It works just as desired. I modified a little the function so I could also know how many mismatches are.
– Carlos Precioso
Jun 3 '11 at 15:43
false for [2,4] [4,2].
– Suraz Khanal
Dec 17 '16 at 7:43
@SurazKhanal Still need to sort
– Aaron McMillin
Mar 15 '17 at 15:13
add a comment |
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?
Thank you! It works just as desired. I modified a little the function so I could also know how many mismatches are.
– Carlos Precioso
Jun 3 '11 at 15:43
false for [2,4] [4,2].
– Suraz Khanal
Dec 17 '16 at 7:43
@SurazKhanal Still need to sort
– Aaron McMillin
Mar 15 '17 at 15:13
add a comment |
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?
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?
edited Dec 19 '16 at 9:31
Hassaan
902816
902816
answered Jun 3 '11 at 15:36
isakkarlsson
937812
937812
Thank you! It works just as desired. I modified a little the function so I could also know how many mismatches are.
– Carlos Precioso
Jun 3 '11 at 15:43
false for [2,4] [4,2].
– Suraz Khanal
Dec 17 '16 at 7:43
@SurazKhanal Still need to sort
– Aaron McMillin
Mar 15 '17 at 15:13
add a comment |
Thank you! It works just as desired. I modified a little the function so I could also know how many mismatches are.
– Carlos Precioso
Jun 3 '11 at 15:43
false for [2,4] [4,2].
– Suraz Khanal
Dec 17 '16 at 7:43
@SurazKhanal Still need to sort
– Aaron McMillin
Mar 15 '17 at 15:13
Thank you! It works just as desired. I modified a little the function so I could also know how many mismatches are.
– Carlos Precioso
Jun 3 '11 at 15:43
Thank you! It works just as desired. I modified a little the function so I could also know how many mismatches are.
– Carlos Precioso
Jun 3 '11 at 15:43
false for [2,4] [4,2].
– Suraz Khanal
Dec 17 '16 at 7:43
false for [2,4] [4,2].
– Suraz Khanal
Dec 17 '16 at 7:43
@SurazKhanal Still need to sort
– Aaron McMillin
Mar 15 '17 at 15:13
@SurazKhanal Still need to sort
– Aaron McMillin
Mar 15 '17 at 15:13
add a comment |
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:
_.isEmpty(_.xor(array1, array2))
Short, simple and pretty!
1
I cannot seem to findxor
in the underscore docs? Are you thinking of IODash?
– Patrick Mencias-lewis
Nov 9 '15 at 18:12
You are right. Edited my response. Thanks Patrick.
– Technotronic
Nov 22 '15 at 9:20
add a comment |
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:
_.isEmpty(_.xor(array1, array2))
Short, simple and pretty!
1
I cannot seem to findxor
in the underscore docs? Are you thinking of IODash?
– Patrick Mencias-lewis
Nov 9 '15 at 18:12
You are right. Edited my response. Thanks Patrick.
– Technotronic
Nov 22 '15 at 9:20
add a comment |
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:
_.isEmpty(_.xor(array1, array2))
Short, simple and pretty!
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:
_.isEmpty(_.xor(array1, array2))
Short, simple and pretty!
edited Nov 22 '15 at 9:19
answered Jan 7 '15 at 10:25
Technotronic
4,52122642
4,52122642
1
I cannot seem to findxor
in the underscore docs? Are you thinking of IODash?
– Patrick Mencias-lewis
Nov 9 '15 at 18:12
You are right. Edited my response. Thanks Patrick.
– Technotronic
Nov 22 '15 at 9:20
add a comment |
1
I cannot seem to findxor
in the underscore docs? Are you thinking of IODash?
– Patrick Mencias-lewis
Nov 9 '15 at 18:12
You are right. Edited my response. Thanks Patrick.
– Technotronic
Nov 22 '15 at 9:20
1
1
I cannot seem to find
xor
in the underscore docs? Are you thinking of IODash?– Patrick Mencias-lewis
Nov 9 '15 at 18:12
I cannot seem to find
xor
in the underscore docs? Are you thinking of IODash?– Patrick Mencias-lewis
Nov 9 '15 at 18:12
You are right. Edited my response. Thanks Patrick.
– Technotronic
Nov 22 '15 at 9:20
You are right. Edited my response. Thanks Patrick.
– Technotronic
Nov 22 '15 at 9:20
add a comment |
Why your code didn't work
JavaScript has primitive data types and non-primitive data types.
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.
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.
Solutions
Two arrays, arr1
and arr2
, have the same members if and only if:
- Everything in
arr2
is inarr1
AND
- Everything in
arr1
is inarr2
So this will do the trick (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.
A solution to your third question
You also asked how to find out which things in arr1
are not contained in arr2
.
This will do it (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
.
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.
Your solutions are wrong. "Two arrays, arr1 and arr2, have the same members if and only if: Everything in arr2 is in arr1 AND Everything in arr1 is in arr2" this is also wrong. This is an array not a set. SosameMembers([1,1,2],[2,1,2]);
should return false.
– Redu
Aug 26 '16 at 8:27
@Redu guess it depends on what "same members" means—I take it to mean "has the same members."sameMembers([1,1,2],[2,1,2])
should returntrue
, in my opinion.sameMembersInOrder([1,1,2],[2,1,2])
AKAdeepEquals([1,1,2],[2,1,2])
should returnfalse
.
– Max Heiber
Aug 26 '16 at 15:40
add a comment |
Why your code didn't work
JavaScript has primitive data types and non-primitive data types.
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.
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.
Solutions
Two arrays, arr1
and arr2
, have the same members if and only if:
- Everything in
arr2
is inarr1
AND
- Everything in
arr1
is inarr2
So this will do the trick (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.
A solution to your third question
You also asked how to find out which things in arr1
are not contained in arr2
.
This will do it (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
.
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.
Your solutions are wrong. "Two arrays, arr1 and arr2, have the same members if and only if: Everything in arr2 is in arr1 AND Everything in arr1 is in arr2" this is also wrong. This is an array not a set. SosameMembers([1,1,2],[2,1,2]);
should return false.
– Redu
Aug 26 '16 at 8:27
@Redu guess it depends on what "same members" means—I take it to mean "has the same members."sameMembers([1,1,2],[2,1,2])
should returntrue
, in my opinion.sameMembersInOrder([1,1,2],[2,1,2])
AKAdeepEquals([1,1,2],[2,1,2])
should returnfalse
.
– Max Heiber
Aug 26 '16 at 15:40
add a comment |
Why your code didn't work
JavaScript has primitive data types and non-primitive data types.
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.
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.
Solutions
Two arrays, arr1
and arr2
, have the same members if and only if:
- Everything in
arr2
is inarr1
AND
- Everything in
arr1
is inarr2
So this will do the trick (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.
A solution to your third question
You also asked how to find out which things in arr1
are not contained in arr2
.
This will do it (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
.
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.
Why your code didn't work
JavaScript has primitive data types and non-primitive data types.
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.
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.
Solutions
Two arrays, arr1
and arr2
, have the same members if and only if:
- Everything in
arr2
is inarr1
AND
- Everything in
arr1
is inarr2
So this will do the trick (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.
A solution to your third question
You also asked how to find out which things in arr1
are not contained in arr2
.
This will do it (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
.
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.
edited Dec 1 '16 at 20:06
answered Jan 2 '16 at 13:49
Max Heiber
4,42713048
4,42713048
Your solutions are wrong. "Two arrays, arr1 and arr2, have the same members if and only if: Everything in arr2 is in arr1 AND Everything in arr1 is in arr2" this is also wrong. This is an array not a set. SosameMembers([1,1,2],[2,1,2]);
should return false.
– Redu
Aug 26 '16 at 8:27
@Redu guess it depends on what "same members" means—I take it to mean "has the same members."sameMembers([1,1,2],[2,1,2])
should returntrue
, in my opinion.sameMembersInOrder([1,1,2],[2,1,2])
AKAdeepEquals([1,1,2],[2,1,2])
should returnfalse
.
– Max Heiber
Aug 26 '16 at 15:40
add a comment |
Your solutions are wrong. "Two arrays, arr1 and arr2, have the same members if and only if: Everything in arr2 is in arr1 AND Everything in arr1 is in arr2" this is also wrong. This is an array not a set. SosameMembers([1,1,2],[2,1,2]);
should return false.
– Redu
Aug 26 '16 at 8:27
@Redu guess it depends on what "same members" means—I take it to mean "has the same members."sameMembers([1,1,2],[2,1,2])
should returntrue
, in my opinion.sameMembersInOrder([1,1,2],[2,1,2])
AKAdeepEquals([1,1,2],[2,1,2])
should returnfalse
.
– Max Heiber
Aug 26 '16 at 15:40
Your solutions are wrong. "Two arrays, arr1 and arr2, have the same members if and only if: Everything in arr2 is in arr1 AND Everything in arr1 is in arr2" this is also wrong. This is an array not a set. So
sameMembers([1,1,2],[2,1,2]);
should return false.– Redu
Aug 26 '16 at 8:27
Your solutions are wrong. "Two arrays, arr1 and arr2, have the same members if and only if: Everything in arr2 is in arr1 AND Everything in arr1 is in arr2" this is also wrong. This is an array not a set. So
sameMembers([1,1,2],[2,1,2]);
should return false.– Redu
Aug 26 '16 at 8:27
@Redu guess it depends on what "same members" means—I take it to mean "has the same members."
sameMembers([1,1,2],[2,1,2])
should return true
, in my opinion. sameMembersInOrder([1,1,2],[2,1,2])
AKA deepEquals([1,1,2],[2,1,2])
should return false
.– Max Heiber
Aug 26 '16 at 15:40
@Redu guess it depends on what "same members" means—I take it to mean "has the same members."
sameMembers([1,1,2],[2,1,2])
should return true
, in my opinion. sameMembersInOrder([1,1,2],[2,1,2])
AKA deepEquals([1,1,2],[2,1,2])
should return false
.– Max Heiber
Aug 26 '16 at 15:40
add a comment |
Object equality check: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
Might suffice for small arrays with flat JSON schemas.
add a comment |
Object equality check: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
Might suffice for small arrays with flat JSON schemas.
add a comment |
Object equality check: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
Might suffice for small arrays with flat JSON schemas.
Object equality check: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
Might suffice for small arrays with flat JSON schemas.
answered Feb 13 '14 at 18:01
Sandeep
20k22320
20k22320
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Jun 3 '11 at 15:37
Andrew
324315
324315
add a comment |
add a comment |
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):
var array1 = [1,2];
var array2 = [2,1];
if(array1.intersect(array2).length === array1.length) {
alert("arrays are the same!");
}
This doesn't work -[1,2].intersect([1,2,3]).length === [1,2].length
returns true. You should compare the length of the original arrays too, I've edited the post to demonstrate.
– GMA
Feb 24 '14 at 3:12
Actually I've just realised my suggested edit doesn't work in the case of duplicates... e.g. it will return false forarray1 = [1,1,2]; array2 = [1,1,2];
... the original answer doesn't fail for that input.
– GMA
Feb 24 '14 at 4:13
ah yes, you're right..
– Erfan
Feb 24 '14 at 9:31
You can do the opposite with_.difference(array1, array2).length;
– Vic
Sep 4 '15 at 20:05
add a comment |
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):
var array1 = [1,2];
var array2 = [2,1];
if(array1.intersect(array2).length === array1.length) {
alert("arrays are the same!");
}
This doesn't work -[1,2].intersect([1,2,3]).length === [1,2].length
returns true. You should compare the length of the original arrays too, I've edited the post to demonstrate.
– GMA
Feb 24 '14 at 3:12
Actually I've just realised my suggested edit doesn't work in the case of duplicates... e.g. it will return false forarray1 = [1,1,2]; array2 = [1,1,2];
... the original answer doesn't fail for that input.
– GMA
Feb 24 '14 at 4:13
ah yes, you're right..
– Erfan
Feb 24 '14 at 9:31
You can do the opposite with_.difference(array1, array2).length;
– Vic
Sep 4 '15 at 20:05
add a comment |
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):
var array1 = [1,2];
var array2 = [2,1];
if(array1.intersect(array2).length === array1.length) {
alert("arrays are the same!");
}
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):
var array1 = [1,2];
var array2 = [2,1];
if(array1.intersect(array2).length === array1.length) {
alert("arrays are the same!");
}
answered Jan 25 '13 at 9:27
Erfan
2,28521119
2,28521119
This doesn't work -[1,2].intersect([1,2,3]).length === [1,2].length
returns true. You should compare the length of the original arrays too, I've edited the post to demonstrate.
– GMA
Feb 24 '14 at 3:12
Actually I've just realised my suggested edit doesn't work in the case of duplicates... e.g. it will return false forarray1 = [1,1,2]; array2 = [1,1,2];
... the original answer doesn't fail for that input.
– GMA
Feb 24 '14 at 4:13
ah yes, you're right..
– Erfan
Feb 24 '14 at 9:31
You can do the opposite with_.difference(array1, array2).length;
– Vic
Sep 4 '15 at 20:05
add a comment |
This doesn't work -[1,2].intersect([1,2,3]).length === [1,2].length
returns true. You should compare the length of the original arrays too, I've edited the post to demonstrate.
– GMA
Feb 24 '14 at 3:12
Actually I've just realised my suggested edit doesn't work in the case of duplicates... e.g. it will return false forarray1 = [1,1,2]; array2 = [1,1,2];
... the original answer doesn't fail for that input.
– GMA
Feb 24 '14 at 4:13
ah yes, you're right..
– Erfan
Feb 24 '14 at 9:31
You can do the opposite with_.difference(array1, array2).length;
– Vic
Sep 4 '15 at 20:05
This doesn't work -
[1,2].intersect([1,2,3]).length === [1,2].length
returns true. You should compare the length of the original arrays too, I've edited the post to demonstrate.– GMA
Feb 24 '14 at 3:12
This doesn't work -
[1,2].intersect([1,2,3]).length === [1,2].length
returns true. You should compare the length of the original arrays too, I've edited the post to demonstrate.– GMA
Feb 24 '14 at 3:12
Actually I've just realised my suggested edit doesn't work in the case of duplicates... e.g. it will return false for
array1 = [1,1,2]; array2 = [1,1,2];
... the original answer doesn't fail for that input.– GMA
Feb 24 '14 at 4:13
Actually I've just realised my suggested edit doesn't work in the case of duplicates... e.g. it will return false for
array1 = [1,1,2]; array2 = [1,1,2];
... the original answer doesn't fail for that input.– GMA
Feb 24 '14 at 4:13
ah yes, you're right..
– Erfan
Feb 24 '14 at 9:31
ah yes, you're right..
– Erfan
Feb 24 '14 at 9:31
You can do the opposite with
_.difference(array1, array2).length;
– Vic
Sep 4 '15 at 20:05
You can do the opposite with
_.difference(array1, array2).length;
– Vic
Sep 4 '15 at 20:05
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
edited Apr 28 '17 at 3:50
answered Jul 8 '15 at 12:08
Manohar Reddy Poreddy
4,6934744
4,6934744
add a comment |
add a comment |
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
This is functionally equivalent to this answer, save for a couple of errors. First, this should all be wrapped within a function, or thereturn
will have no effect. Second, you should check the sorted arrays, as[1,2]
and[2,1]
will be detected as not the same. Third and most important, this will actually only check if some element is the same. The conditional should beif (array1!==array2) {return false;}
. Maybe this can help you in the future!
– Carlos Precioso
May 3 '18 at 17:10
And as an extra comment, do try to use indentation for better understanding of the code flow, as well as clearer variable names. E.g.:array1
andarray2
could be renamedelem1
andelem2
. Both these tips will save you plenty of headaches in the future!
– Carlos Precioso
May 3 '18 at 17:17
1
On further inspection, why the double loop? Both arrays should be the same length, and if not, they are directly not equal. This way you can use only one loop. Right now, this code checks if any of the elements of the first array are anywhere in the second one. Check this answer to see how you should implement it. Good luck in your JavaScript journey!
– Carlos Precioso
May 3 '18 at 17:23
add a comment |
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
This is functionally equivalent to this answer, save for a couple of errors. First, this should all be wrapped within a function, or thereturn
will have no effect. Second, you should check the sorted arrays, as[1,2]
and[2,1]
will be detected as not the same. Third and most important, this will actually only check if some element is the same. The conditional should beif (array1!==array2) {return false;}
. Maybe this can help you in the future!
– Carlos Precioso
May 3 '18 at 17:10
And as an extra comment, do try to use indentation for better understanding of the code flow, as well as clearer variable names. E.g.:array1
andarray2
could be renamedelem1
andelem2
. Both these tips will save you plenty of headaches in the future!
– Carlos Precioso
May 3 '18 at 17:17
1
On further inspection, why the double loop? Both arrays should be the same length, and if not, they are directly not equal. This way you can use only one loop. Right now, this code checks if any of the elements of the first array are anywhere in the second one. Check this answer to see how you should implement it. Good luck in your JavaScript journey!
– Carlos Precioso
May 3 '18 at 17:23
add a comment |
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;
}
}
}
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;
}
}
}
answered Aug 8 '17 at 7:36
Vinoth
497221
497221
1
This is functionally equivalent to this answer, save for a couple of errors. First, this should all be wrapped within a function, or thereturn
will have no effect. Second, you should check the sorted arrays, as[1,2]
and[2,1]
will be detected as not the same. Third and most important, this will actually only check if some element is the same. The conditional should beif (array1!==array2) {return false;}
. Maybe this can help you in the future!
– Carlos Precioso
May 3 '18 at 17:10
And as an extra comment, do try to use indentation for better understanding of the code flow, as well as clearer variable names. E.g.:array1
andarray2
could be renamedelem1
andelem2
. Both these tips will save you plenty of headaches in the future!
– Carlos Precioso
May 3 '18 at 17:17
1
On further inspection, why the double loop? Both arrays should be the same length, and if not, they are directly not equal. This way you can use only one loop. Right now, this code checks if any of the elements of the first array are anywhere in the second one. Check this answer to see how you should implement it. Good luck in your JavaScript journey!
– Carlos Precioso
May 3 '18 at 17:23
add a comment |
1
This is functionally equivalent to this answer, save for a couple of errors. First, this should all be wrapped within a function, or thereturn
will have no effect. Second, you should check the sorted arrays, as[1,2]
and[2,1]
will be detected as not the same. Third and most important, this will actually only check if some element is the same. The conditional should beif (array1!==array2) {return false;}
. Maybe this can help you in the future!
– Carlos Precioso
May 3 '18 at 17:10
And as an extra comment, do try to use indentation for better understanding of the code flow, as well as clearer variable names. E.g.:array1
andarray2
could be renamedelem1
andelem2
. Both these tips will save you plenty of headaches in the future!
– Carlos Precioso
May 3 '18 at 17:17
1
On further inspection, why the double loop? Both arrays should be the same length, and if not, they are directly not equal. This way you can use only one loop. Right now, this code checks if any of the elements of the first array are anywhere in the second one. Check this answer to see how you should implement it. Good luck in your JavaScript journey!
– Carlos Precioso
May 3 '18 at 17:23
1
1
This is functionally equivalent to this answer, save for a couple of errors. First, this should all be wrapped within a function, or the
return
will have no effect. Second, you should check the sorted arrays, as [1,2]
and [2,1]
will be detected as not the same. Third and most important, this will actually only check if some element is the same. The conditional should be if (array1!==array2) {return false;}
. Maybe this can help you in the future!– Carlos Precioso
May 3 '18 at 17:10
This is functionally equivalent to this answer, save for a couple of errors. First, this should all be wrapped within a function, or the
return
will have no effect. Second, you should check the sorted arrays, as [1,2]
and [2,1]
will be detected as not the same. Third and most important, this will actually only check if some element is the same. The conditional should be if (array1!==array2) {return false;}
. Maybe this can help you in the future!– Carlos Precioso
May 3 '18 at 17:10
And as an extra comment, do try to use indentation for better understanding of the code flow, as well as clearer variable names. E.g.:
array1
and array2
could be renamed elem1
and elem2
. Both these tips will save you plenty of headaches in the future!– Carlos Precioso
May 3 '18 at 17:17
And as an extra comment, do try to use indentation for better understanding of the code flow, as well as clearer variable names. E.g.:
array1
and array2
could be renamed elem1
and elem2
. Both these tips will save you plenty of headaches in the future!– Carlos Precioso
May 3 '18 at 17:17
1
1
On further inspection, why the double loop? Both arrays should be the same length, and if not, they are directly not equal. This way you can use only one loop. Right now, this code checks if any of the elements of the first array are anywhere in the second one. Check this answer to see how you should implement it. Good luck in your JavaScript journey!
– Carlos Precioso
May 3 '18 at 17:23
On further inspection, why the double loop? Both arrays should be the same length, and if not, they are directly not equal. This way you can use only one loop. Right now, this code checks if any of the elements of the first array are anywhere in the second one. Check this answer to see how you should implement it. Good luck in your JavaScript journey!
– Carlos Precioso
May 3 '18 at 17:23
add a comment |
Using ES6
We'll use Ramda's equals
function, but instead we can use Lodash's or Underscore's isEqual
:
const R = require('ramda');
const arraysHaveSameValues = (arr1, arr2) => R.equals( [...arr1].sort(), [...arr2].sort() )
Using the spread opporator, we avoid mutating the original arrays, and we keep our function pure.
add a comment |
Using ES6
We'll use Ramda's equals
function, but instead we can use Lodash's or Underscore's isEqual
:
const R = require('ramda');
const arraysHaveSameValues = (arr1, arr2) => R.equals( [...arr1].sort(), [...arr2].sort() )
Using the spread opporator, we avoid mutating the original arrays, and we keep our function pure.
add a comment |
Using ES6
We'll use Ramda's equals
function, but instead we can use Lodash's or Underscore's isEqual
:
const R = require('ramda');
const arraysHaveSameValues = (arr1, arr2) => R.equals( [...arr1].sort(), [...arr2].sort() )
Using the spread opporator, we avoid mutating the original arrays, and we keep our function pure.
Using ES6
We'll use Ramda's equals
function, but instead we can use Lodash's or Underscore's isEqual
:
const R = require('ramda');
const arraysHaveSameValues = (arr1, arr2) => R.equals( [...arr1].sort(), [...arr2].sort() )
Using the spread opporator, we avoid mutating the original arrays, and we keep our function pure.
answered Aug 1 '18 at 15:32
Ben Carp
866820
866820
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f6229197%2fhow-to-know-if-two-arrays-have-the-same-values%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
I am pretty certain you need to go through each element of the arrays.
– Thomas Li
Jun 3 '11 at 15:35
Do you know why it returns false? Curious.
– RobW
Jun 1 '14 at 19:50
See @Andrew 's answer stackoverflow.com/a/6229263/702565
– Carlos Precioso
Jun 3 '14 at 22:32
possible duplicate of how to check javascript array equals?
– Palec
Jun 24 '14 at 14:41