How To Check If Array Includes A Value In JavaScript? - Samantha Ming
Maybe your like
Here's a Code Recipe to check if a #JavaScript array contains a value. You can use the new array includes method 😋 For older browsers and IE, you can use indexOf 👍
const array = ['🥗', '🍔', '🍰']; // Modern Browser array.includes('🍰'); // true // Older Browser array.indexOf('🍰') !== -1; // true# includes with other primitive types
Besides strings, includes also works great with other primitive types .
const symbol = Symbol('symbol'); const array = [ 'string', 200, 0, undefined, null, symbol ];Using includes
array.includes('string'); // true array.includes(200); // true array.includes(0); // true array.includes(undefined); // true array.includes(null); // true array.includes(symbol); // trueUsing indexOf
array.indexOf('string') !== -1; // true array.indexOf(200) !== -1; // true array.indexOf(0) !== -1; // true array.indexOf(undefined) !== -1; // true array.indexOf(null) !== -1; // true array.indexOf(symbol) !== -1; // true# Caveats of indexOf
So far, I have shown you values where both includes and indexOf work interchangeably. However, there is one value, where they differ 🤭
const array = [NaN]; // ✅ array.includes(NaN); // true // 😱 array.indexOf(NaN) !== -1; // false# Checking for Array of Objects using some()
For a more versatile solution that works on other data types, you may want to use some instead.
const array = ['🥗', '🍔', '🍰']; array.some(food => food === '🍰'); // true".some()": tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
This method is ideal for an array of objects.
const array = [{ name: 'js' }, { name: 'css' }]; array.some(code => code.name === 'js'); // true array.some(code => code.name === '🤖'); // falseIn a previous code note, I talked about a quick & dirty way to check objects using JSON.stringify().
How to Compare 2 Objects in JavaScript
Taking that concept, we can also use it to compare object element in an array like this:
const array = [{ name: 'js' }, { name: 'css' }]; array.some(code => JSON.stringify(code) === JSON.stringify({ name: 'css' })); // true# Case Sensitive
Both includes and indexOf are case sensitive:
const array = ['SAMANTHA']; array.includes('samantha'); // false array.indexOf('samantha') !== -1; // falseTo make it case insensitive, you could consider changing the case of the array like so:
const array = ['SAMANTHA']; const sameCaseArray = array.map(value => value.toLowerCase()); // ['samantha'] sameCaseArray.includes('samantha'); // true sameCaseArray.indexOf('samantha') !== -1; // trueBut if you were using some, you can do it in one line:
const array = ['SAMANTHA']; array.some(value => value.toLowerCase() === 'samantha'); // true# Browser Support
Support for includes is really good for all modern browsers. However, if you need IE or older browser, you will need to use indexOf.
Can I use? Array.prototype.includes
# Community Input
@lolinoid: contains > @prvnbist That's a method DOM Nodes, most known example for it would be getting a list of classnames which will be a node list then you can use contain method to see if it has a classname. Or you can convert it to an array and then use includes method
You can use the in operator to loop over an object to check if a specific property key exists. (Knowledge shared by @fvbix)
@pixelfixer : And if you want the value returned, you can use Array.find()
Performance test > array indexOf vs includes . Thanks @equiman :
@smokku: You can avoid all these !== -1 comparison using ~ operator
@danvc: ~[].indexOf(value). The bitwise ~ operator will return a truthy value for anything but -1. Negating it is as simple as doing !~.
@smokku : Bitwise not gives you the opposite of the number, but we use two's complement system to avoid having a +0 and -0. So the negative numbers are shifted by one - where -1 takes place of -0. When we negate the -1 we get +0, which is the only falsey value. All other indices we can get of indexOf() will give you a truthy (non-zero) value when passed through bitwise not ~.
@smokku : If you are interested in diving this deep, I highly recommend a book by Charles Petzold called "Code: The Hidden Language of Computer Hardware and Software". It is a fun read, that will guide you from the basics of code design (like Morse, Braile, etc.) through electrical switches and flashing lightbulbs, telegraph, electronic gates and flip-flops, up to the simple CPU level.
# Resources
- MDN Web Docs: includes
- MDN Web Docs: indexOf
- Stack Overflow: How do I check if an array includes a value in JavaScript?
- MDN Web Docs: some
- w3schools: contains
- MDN Web Docs: in operator
Tag » Add Element If Not In Array Javascript
-
Array.push() If Does Not Exist? - Stack Overflow
-
Array.push() Element If Does Not Exist Using JavaScript | Bobbyhadz
-
Js Add To Array If Not Exists Code Example
-
Push To Array If Not Exist Javascript Code Example - Code Grepper
-
5 Way To Append Item To Array In JavaScript
-
How To Check If A Value Exists In An Array In JavaScript
-
totype.push() - JavaScript - MDN Web Docs
-
Array - JavaScript - MDN Web Docs
-
Check If An Item Is In An Array In JavaScript - FreeCodeCamp
-
JavaScript Array Includes() Method - W3Schools
-
Array Methods - The Modern JavaScript Tutorial
-
Add An Item To The Beginning Of An Array In JavaScript Or Node.js
-
Check If The Value Exists In Array In Javascript - Javatpoint
-
Javascript Array Push: How To Add Element In Array - AppDividend
-
How To Check If Key Exists In JavaScript Object/Array - Stack Abuse
-
How To Add Elements Into An Array In JavaScript - Linux Hint
-
How To Check If Value Exists In An Array Using Javascript? - Flexiple
-
JavaScript Arrays - Tips, Tricks And Examples - CodinGame