2

I want to know about some function (if any) or library which may provide direct functions to find the type of elements in an array.

Suppose I have an array containing elements of same data type :

var sameArray = [1, 2, 3, 4];
var diffArray = ['a', 'b', 'c', 4];

sameArray.itemPrototype();  // Returns int
diffArray.itemPrototype();  // Returns undefined

For first array, it should return int and for the second one undefined or false.

3
  • 1
    what is itemPrototype?...Any custom function you wrote? Commented Apr 6, 2015 at 5:37
  • 1
    Its just a dummy name. I haven't made any implementation yet. And I will prefer using a in-built function in some existing library. Commented Apr 6, 2015 at 7:04
  • Ok..For first one, expected output should be int, but as second case have multiple types present, so expected output should be undefined as you mentioned..Right? If thats the case, you can simply write a custom function, probably using typeof inside it.. Commented Apr 6, 2015 at 7:23

1 Answer 1

2

For arrays with primitives (like numbers, strings) you may use a simple method:

function getItemsType(arr) {
  var itemType, i;

  for (i=0; i < arr.length; i++) {
    if (typeof itemType === 'undefined') {
      itemType = typeof arr[i];
    } else if (itemType !== typeof arr[i]) {
      return undefined;
    }
  }

  return itemType;
}

In this jsbin you'll find a function implementation and integration into Array.prototype.

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

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.