Home > Backend Development > PHP Tutorial > How to Check if an Array Contains Another Array in JavaScript?

How to Check if an Array Contains Another Array in JavaScript?

Patricia Arquette
Release: 2024-11-19 20:03:03
Original
234 people have browsed it

How to Check if an Array Contains Another Array in JavaScript?

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;
}
Copy after login

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;
}
Copy after login

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;
}
Copy after login

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');
}
Copy after login

Output:

ph was found
o was found
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template