15

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

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
parth
  • 624
  • 1
  • 10
  • 29

5 Answers5

24

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);
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
  • @parth, `some` method provide a callback test function for ever item from the array. The `test` function check if array item is object. The `condition` is if `typeof a` is object.`some` method returns true if `at least` one item from the array satifiy the condition. – Mihai Alexandru-Ionut Oct 10 '17 at 10:36
5

I want to check if array contains object or not

Use some to simply check if any item of the array has value of type "object"

var hasObject = $arr.some( function(val){
   return typeof val == "object";
});
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
1

var hasObject = function(arr) {
  for (var i=0; i<arr.length; i++) {
    if (typeof arr[i] == 'object') {
      return true;
    }
  }
  return false;
};

console.log(hasObject(['a','b','c']));
console.log(hasObject([{ id: 1}, {id: 2}]));
console.log(hasObject([{id: 1}, {id:2}, 'a', 'b']));
0

You could count the objects and use it for one of the three types to return.

function getType(array) {
    var count = array.reduce(function (r, a) {
        return r + (typeof a === 'object');
    }, 0);
    
    return count === array.length
        ? 'array of objects'
        : count
            ? 'mix values'
            : 'normal';
}

console.log([
    ['a', 'b', 'c'],
    [{ id: 1 }, { id: 2 }],
    [{ id: 1 }, { id: 2 }, 'a', 'b']
].map(getType));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

With a type check on array

const hasObject = a => Array.isArray(a) && a.some(val => typeof val === 'object')
Gorky
  • 1,393
  • 19
  • 21