How to check if an array includes an object in JavaScript ?
There are various methods to check an array includes an object or not.
Using includes() Method: If array contains an object/element can be determined by using includes() method. This method returns true if the array contains the object/element else return false.
Syntax:
array.includes( element/object, startingPosition )
Example:
Javascript
var obj = { "geeks1" :10, "geeks2" :12} var gfg = [ "geeks1" , "geeks2" , obj]; /* Use JavaScript includes() method */ var num = gfg.includes(obj, 0); console.log(num) |
Output:
true
Using some() Method: The some() method uses the function for its evaluation and it executes the function once for each element present in the array. If it finds the object/element in the array then it returns true and stop the execution for remaining elements otherwise return false.
Syntax:
array.some( function(currValue, arrIndex, arrObj), this )
Example:
Javascript
var arr = [ "geeks1" , "geeks2" , "geeks3" , {1: "geeks4" , 2: "geeks5" }]; var boolVar = arr.some( value => { return typeof value == "object" } ); console.log(boolVar); |
Output:
true
Using filter() Method: The filter() method creates the array of all those elements/objects that passes the checking condition.
Syntax:
array.filter( function(currValue, arrIndex, arrObj), this )
Example:
Javascript
var obj = { "geeks1" :10, "geeks2" :12} var arr = [ "geeks1" , "geeks2" , "geeks3" , obj]; if (arr.filter(value=> value==obj).length > 0) console.log( "true" ); else console.log( "false" ); |
Output:
true
Using findIndex() Method: The findIndex() method returns the position of searched object/element if it present in the array and stop the execution for rest elements. If the element/object not found then return -1.
Syntax:
array.findIndex( function(currValue, arrIndex, arrObj), this )
Example:
html
var arr = ["geeks1", "geeks2", "geeks3", {"geeks1":10, "geeks2":12}]; var num = arr.findIndex( value => { return typeof value == "object" } ); console.log("Object found at position: " + num); |
Output:
Object found at position: 3
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
Please Login to comment...