17

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

5
  • will it always be id? or it can change? Commented Oct 10, 2017 at 9:39
  • Loop through array items and test if it's object stackoverflow.com/questions/8511281/… Commented Oct 10, 2017 at 9:40
  • Are you looking for a specific value, or just if the array contains "any object"? Commented Oct 10, 2017 at 9:42
  • @shv22 .object can be anything Commented Oct 10, 2017 at 9:43
  • @Cerbrus just want check if array contains an object. Commented Oct 10, 2017 at 9:43

5 Answers 5

26

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);

Sign up to request clarification or add additional context in comments.

1 Comment

@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.
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";
});

Comments

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']));

Comments

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));

Comments

0

With a type check on array

const hasObject = a => Array.isArray(a) && a.some(val => typeof val === 'object')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.