Can You Check if an Array Contains Another in JavaScript?
Similar to PHP's in_array() function, which compares values from one array against another, JavaScript does not have a built-in equivalent for this functionality.
Workarounds
To address this gap, popular JavaScript libraries and utility packages provide their own implementations. jQuery's $.inArray() and Prototype's Array.indexOf() are notable examples. jQuery's implementation is straightforward:
function inArray(needle, haystack) { for (var i = 0; i < haystack.length; i++) { if (haystack[i] == needle) return true; } return false; }
Array Comparison
However, it's important to note that PHP's in_array() also determines if one array is within another. Chris's and Alex's code does not replicate this behavior. Instead, Chris's code is similar to PHP's array_intersect, while Alex's is Prototype's official version of indexOf.
To implement PHP's in_array() for nested arrays, the following custom function can be used:
function arrayCompare(a1, a2) { if (a1.length != a2.length) return false; for (var i = 0; i < a1.length; i++) { if (a1[i] !== a2[i]) return false; } return true; }
Enhanced inArray() Function:
function inArray(needle, haystack) { for (var i = 0; i < haystack.length; i++) { if (typeof haystack[i] == 'object') { if (arrayCompare(haystack[i], needle)) return true; } else { if (haystack[i] == needle) return true; } } return false; }
Example Usage
var a = [['p', 'h'], ['p', 'r'], 'o']; if (inArray(['p', 'h'], a)) { alert('ph was found'); } if (inArray(['f', 'i'], a)) { alert('fi was found'); } if (inArray('o', a)) { alert('o was found'); }
Output:
ph was found o was found
Please note that extending the Array prototype is not recommended, as it can have unintended consequences.
The above is the detailed content of How to Check if an Array Contains Another Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!