Here's a Code Recipe to check if a #JavaScript array contains a value. You can use the new array 3 method π For older browsers and IE, you can use 4 π Show
const symbol = Symbol('symbol'); const array = [ 'string', 200, 0, undefined, null, symbol ]; 3 with other primitive typesBesides strings, 3 also works great with other primitive types.
Using 3
Using 4
Caveats of const symbol = Symbol('symbol'); const array = [ 'string', 200, 0, undefined, null, symbol ]; 4So far, I have shown you values where both 3 and 4 work interchangeably. However, there is one value, where they differ π€
Checking for Array of Objects using array.includes('string'); // true array.includes(200); // true array.includes(0); // true array.includes(undefined); // true array.includes(null); // true array.includes(symbol); // true 2For a more versatile solution that works on other data types, you may want to use 3 instead.
This method is ideal for an array of objects.
In a previous code note, I talked about a quick & dirty way to check 4 using 5.
Taking that concept, we can also use it to compare object element in an array like this:
Case SensitiveBoth 3 and 4 are case sensitive:
To make it case insensitive, you could consider changing the case of the array like so:
But if you were using 3, you can do it in one line: 0Browser SupportSupport for 3 is really good for all modern browsers. However, if you need IE or older browser, you will need to use 4.Can I use? Community Input
1
2
|