Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if array contains at least one object ?

I want to check if array contains object or not. I am not trying to compare values just want to check in my array if object is present or not?

Ex.

$arr = ['a','b','c'] // normal
$arr = [{ id: 1}, {id: 2}] // array of objects
$arr = [{id: 1}, {id:2}, 'a', 'b'] // mix values

So how can i check if array contains object

like image 639
parth Avatar asked Oct 10 '17 09:10

parth


People also ask

How do you check if an array has at least one element?

some() The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false.

How do you find the minimum value of an array of objects?

Now that we have a simple Array of numbers, we use Math. min() or Math. max() to return the min/max values from our new Y value array. The spread operator allows us to insert an array into the built in function.

How do you check if an array contains a value in another array?

Use the inbuilt ES6 function some() to iterate through each and every element of first array and to test the array. Use the inbuilt function includes() with second array to check if element exist in the first array or not. If element exist then return true else return false.


1 Answers

You can use some method which tests whether at least one element in the array passes the test implemented by the provided function.

let arr = [{id: 1}, {id:2}, 'a', 'b'];
let exists = arr.some(a => typeof a == 'object');
console.log(exists);
like image 164
Mihai Alexandru-Ionut Avatar answered Oct 24 '22 05:10

Mihai Alexandru-Ionut