Checking if an Object Exists in an Array
The includes()
method in JavaScript allows you to check if a value exists in an array.
For primitive types, you can do:
const primitiveArray = [1,2,3,4,5]
primitiveArray.includes(3)
> true
You can also pass a second optional argument to includes()
defining the first index of the search.
Does 4 exists in the array after the second index position?
primitiveArray.includes(4, 2)
> true
includes()
can also be used with objects, however, includes()
checks for the reference of the object in memory, and not for its value.
The following will return false:
const objectArray = [{1:1},{2:2},{3:3}]
objectArray.includes({1:1})
>false
To compare same-reference objects in an array, you can have them defined before creating the array. By doing that, the elements in the array and the object created will point to the same location in memory, hence being comparable by includes()
const a = {1: 1}
const b = {2: 2}
const c = {3: 3}
const Array = [a, b, c]
Array.includes(a)
> true
Array.includes(b)
> true
Array.includes(b, 1)
> true
Array.includes(b, 12)
false