I have a 2D array and two 1D arrays. I have to compare the 1D array with the 2D array in JavaScript. I have written the following code but it is not working. Any help would be appreciated.
<!DOCTYPE html>
<html>
<body>
<script>
var arr = [
['Cat', 'Brown', 2],
['Parrot', 'Brown', 1]
];
var col = [0,1];
var key = ['Parrot','Brown'];
for (var i = 0; i < arr.length; i++){
for (var j = 0; j < col.length; j++){
var isMatched = arr[i][col[j]] == key[j];
if (isMatched){
// write arr index
document.write(i);
// it should write 1 but writing 001
}
}
}
</script>
</body>
</html>
I am using 'col' array to store index of columns to be compared like in this case 0 for first column with values cat, parrot and so on. What I need is if all elements of 'key' array matches with any array of 'arr' then it should print true and index of matching array in 'arr'
Based on what you've mentioned in the comments, if you just want to check whether all the values in key
array are contained in the other list of arrays arr
. Then you don't necessarily need a col
array and the following script should work.
var arr = [
["Cat", "Brown", 2],
["Parrot", "Brown", 1],
];
var key = ["Parrot", "Brown"];
for (let i = 0; i < arr.length; i++) {
// Current array from array of arrays, which you want to search
let array_to_be_searched = arr[i];
// Let's initially assume that all the elements of the key are included in this one
let isMatched = true;
for (let j = 0; j < key.length; j++) {
if (!array_to_be_searched.includes(key[j])) {
isMatched = false;
break;
}
}
// If our assumption is correct
if (isMatched) {
document.write(true); // Write true :)
document.write(i); // Index of current array
}
}
The output you are getting is "011" and not "001" are the index of "parrot" in key and then two time the index of "brown" in key. After reading you comment I understood that you meant that "parrot" and "brown" should be found as a set in on of arr sub arrays.
So you have made the wrong comparisons - check this answerer to do the right one - Check if an array contains any element of another array in JavaScript
and them make one loop to make the comparison.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.