Javascript equivalent of PHP's in_array()
If you're looking for an equivalent of PHP's in_array()
in JavaScript, Array.includes()
would be a straightforward solution to check whether an element exists in an array, as shown below.
In case you're dealing with older browsers like IE9 and below, go for Array.indexOf()
which returns the first index at which the given element is found in the array, or -1 if not present.
Older Browser Support
If your project needs to support older browsers, and you wish to have the PHP's in_array()
equivalent function that still works with those elderlies, here's your polyfill for Array.includes()
.
It ensures that includes()
is available even in those internet dinosaurs.
If you want to go Pro: Deep Equality Check
Both includes
and indexOf
perform a shallow comparison meaning if you threw at them a chunk of complex data, they would sadly fail. Fret not, with a recursive arrayCompare function, you can have your own deep equality version.
Visualising it with a Classic Example
Let's pretend we're at a book club with an array of books:
When we're asking:
JavaScript provides includes()
to verify:
Every JavaScript lover will agree:
Going Off-road: Manual Implementation
Sometimes we need to go the old-fashioned way. Despite the convenience of includes
and indexOf
, there could be scenarios where a custom manual implementation might be preferable:
-
Performance Intensive Situations: When dealing with an army of data, a custom function using for-loops or while-loops could be optimized better, kind of like creating a superhero with a special power!
-
Non-Primitive Mischief: If your mix includes objects, functions or arrays, they are complex and would need your coding skills to whip up a custom solution.
-
Extensible code: If you're laying down the infrastructure for a library or a framework, a custom in-array check function that fits nicely with your design might be your best bet.
Avoiding the Traps: Prototype Pollution
While adding custom methods, steer clear of extending the Array.prototype
directly. It's a path leading to conflicts with libraries or curious bugs popping up in your codebase. So, instead of increasing your debugging time, define a utility function that acts as a savior!
Your global scope remains clean, and conflicts are avoided. A win-win!
Was this article helpful?