Evaluating Javascript Arrays
arrays, extjs, javascript
Solution
Comparing the two arrays using `==` or `===` will not work because they are not the same object. If you want to determine the element-wise equality of two arrays you need to compare the arrays element-wise.
I doubt you'll gain anything from using tricks like `join(',')` and then using string operations. The following should work though:
function arraysAreEqual (a, b) {
if (a.length != b.length) {
return false;
}
for (var i=0; i<a.length; i++) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
function containsArray (arrays, target) {
for (var i=0; i<arrays.length; i++) {
if (arraysAreEqual(arrays[i], target)) {
return true;
}
}
return false;
}
var arraysToSearch = [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]];
var newArray = [1, 2, 3];
containsArray(arraysToSearch, newArray);
Problem
I have an array that contains an array of arrays if that makes any sense. so for example: ``` [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]] ``` I want to see whether an array exists withing the array, so if [1, 2, 3] is duplicated at all. I have tried to use the .indexOf method but it does find the duplicate. I have also tried Extjs to loop through the array manually and to evaluate each inner array, this is how I did it: ``` var arrayToSearch = [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]; var newArray = [1, 2, 3]; Ext.each(arrayToSearch, function(entry, index){ console.log(newArray, entry); if(newArray == entry){ console.log(index); }; }); ``` This also does not detect the duplicate. the console.log will output [1, 2, 3] and [1, 2, 3] but will not recognize them as equal. I have also tried the === evaluator but obviously since == doesn't work the === wont work. I am at wits end, any suggestions.