I am learning Javascript, and I saw a function on SO for comparing arrays to check if they are same. However, my current function returns false if the two arrays are [string1,string2] & [string2,string1]. Basically, the two positions are interchanged. The code is as follows:
function _compareArrays(arr1,arr2){
var result = arr1 != null && arr2 != null && arr1.length == arr2.length && arr1.every(function(element) {
return arr2.indexOf(element);
});
return result ;
}
However, I want these two arrays to be returned as same. So, I changed .every to .indexOf() and it seemed to work. But, I have a doubt, how exactly is the counter getting incremented here to make sure the comparison is being done for every element?
I mean, like, in C++, we do,
for (int i = 0; i < 10; i++)
if (arr1[i] == arr2[i]
cout<<"Elements are same\n";
Here, I have an explicit i++ which increments the counter. How does it happen in the above function?
Thanks!
indexOfdoes not take a function as an argument in any documentation I've ever read -So, I changed .every to .indexOf()when you have a flat tyre, do you replace the wheel with a banana?_compareArraysmethod you've defined always returns -1. As for how theeverymethod iterates without explicitly incrementing a counter: It's a function on the Array prototype that does the itteration automatically. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…