I Have an array holding multiple objects. Is it posible to check if a value exists in any one of the objects e.g. id->27 without looping? In a similar fashion to PHP's in_array() function. Thanks.
> array(10)[0]=>Object #673
["id"]=>25
["name"]=>spiderman
[1]=>Object #674
["id"]=>26
["name"]=>superman
[2]=>Object #675
["id"]=>27
["name"]=>superman
.......
.......
.........
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.
Use the includes() method to check if an array contains a value in TypeScript, e.g. if (arr. includes('two')) {} . The includes method will return true if the value is contained in the array and false otherwise.
The Array.isArray() static method determines whether the passed value is an Array .
For primitive values, use the array. includes() method to check if an array contains a value. For objects, use the isEqual() helper function to compare objects and array. some() method to check if the array contains the object.
No. If you often need quick direct lookup of values, you need to use array keys for them, which are lightning fast to lookup. For example:
// prepare once
$indexed = array();
foreach ($array as $object) {
$indexed[$object->id] = $object;
}
// lookup often
if (isset($indexed[42])) {
// object with id 42 exists...
}
If you need to lookup objects by different keys, so you can't really index them by one specific key, you need to look into different search strategies like binary searches.
$results = array_filter($array, function($item){
return ($item->id === 27);
});
if ($results)
{
.. You have matches
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With