Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript how to detect weather the type is Array or Object? [duplicate]

I need to know how to check the variable if its an Array or its an Object

var arr = ['foo', 'bar'];
var obj = {
  0: 'foo',
  1: 'bar'
}

document.write('arr is an: ' + typeof arr + ', obj is an: ' + typeof obj)

// The result is always:
// arr is an: object, obj is an: object

Is there any way to tell the difference between the two types?

like image 610
Mustafa Dwekat Avatar asked Feb 23 '16 13:02

Mustafa Dwekat


People also ask

How do you check if an array of objects has duplicate values in JavaScript?

Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.

How do you check if an object is an array or not in JavaScript?

isArray() method is used to check if an object is an array. The Array. isArray() method returns true if an object is an array, otherwise returns false .

Why typeof array is object in JavaScript?

This because in javascript all derived data type is always a type object. Included functions and array. In case you need to check if it's an array you can use isArray method of Array. and the result will be the same as the previous one.


1 Answers

Array.isArray(arr) will return true. Array.isArray(obj) will return false.

like image 87
sahbeewah Avatar answered Nov 14 '22 23:11

sahbeewah