+ 1
Problem comparing arrays
Why does the code return false, what is the correct way to compare the arrays? https://code.sololearn.com/cDnaAsGCRBNT/?ref=app
11 Antworten
+ 11
Tนktนk💕
When you copy an answer from chatGPT or another user, you need to give ***credits***. It is not fair to pretend that it was your own effort.
+ 8
there is also a way of comparing arrays by using a for loop. the for loop generates index values, that can be used to do the comparison:
var arr1 = [1, 2, 3];
var arr2 = [1, 2, 3];
//var arr2 = [1, 5, 2]
var isequal = true;
for (var ndx = 0; ndx < arr1.length; ndx++) {
if (arr1[ndx] !== arr2[ndx]) {
isequal = false
break;
}
}
console.log(isequal);
+ 4
Here are some ways (under the js tab) that others have done it.
If I remember correctly, your code is trying to compare two objects and see if they exist in the same place. Since you've declared/initialised both of them, they don't, so they aren't considered equal.
https://code.sololearn.com/WCaeDqcUP2z2/?ref=app
https://code.sololearn.com/W5X3XTjvMluM/?ref=app
https://code.sololearn.com/WNXz28qqbIU0/?ref=app
https://code.sololearn.com/WoFYVaginJIm/?ref=app
+ 4
thank you very much
+ 3
NinjaGamer
The code returns false because the == operator does not work for comparing arrays in JavaScript.
you can use the JSON.stringify method to convert the arrays to strings and then compare the strings.
example of how you can use it:
' ' '
var arr1 = [1, 2, 3];
var arr2 = [1, 2, 3];
console.log(JSON.stringify(arr1) === JSON.stringify(arr2));
' ' '
https://www.geeksforgeeks.org/how-to-compare-two-arrays-in-javascript/
hope it's helpful 👍..
+ 2
Ausgrindtube Tนktนk💕 So there is no native way to compare arrays
+ 2
yes, comparing arrays is a pain.
also:
let arr1 = [1,2,3]
let arr2 = [1,2,3]
console.log(arr1.length === arr2.length && arr1.every((v, i) => v === arr2[i]));
useful links:
https://www.freecodecamp.org/news/how-to-compare-arrays-in-javascript/
https://sebhastian.com/javascript-compare-array/#:~:text=In%20order%20to%20compare%20array,()%20and%20includes()%20method.&text=The%20includes()%20method%20are,()%20method%20as%20an%20alternative.
more discussion at SO
https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript
+ 1
Lisa chatGPT🤔..just google it.
https://www.geeksforgeeks.org/how-to-compare-two-arrays-in-javascript/
+ 1
It returns false since you cannot compare arrays. Arrays are objects. Objects, when compared, always return false. However, there are ways to make it compare:
1. toString() function. Basically converting arrays into strings
Ex:
console.log(arr1.toString() == arr2.toString())
2. JSON.stringify function
Ex:
let js1 = JSON.stringify(arr1);
let js2 = JSON.stringify(arr2);
console.log(js1==js2);
+ 1
Rashid Start a course. If you have a particular question, create your own thread.
+ 1
Thanks Lisa actually I am biginner*****