Easily Find Out The Length Of Object, Array or String

Author : Code With Mark

Often times you get data from many different sources. It would be helpful to know the length of the data. That would help you determine whether to go in direction A or B.

Learn to easily find the length of your data whether it’s a string, object or array.

Below is a simple and easy to use JavaScript function that will help you quickly find out the size of  your data.

var size = function (data)
	var text = data.constructor.toString()	 
	var str = (text.match(/function (.*)\(/)[1]).toLowerCase();
	if(str ==="number" || str ==="string")
		var d1 = str.toString()
		return data.toString().length 
	else if(str ==="object" || str ==="array")
		return Object.keys(data).length

Let’s suppose you have the following data:

var str = "123"
var obj = {a:2, b:2}
var arr = ["0", "1", "2",'arr']

To find out the length of each data type you would simply call it like this:

console.log( 'str -> ' + size(str) ) //--> str -> 3
console.log( 'obj -> '  + size(obj) ) //--> obj -> 2
console.log( 'arr -> ' + size(arr) ) //--> arr -> 4


Results for your:

  • String data, the length is only 3.
  • Object data, the length is only 2.
  • Array data, the length is only 4.


Once you start using this function, you will start to see it will make your life a lot easier.

Sharing is caring:            

You might also like

How to detect pressing Enter on keyboard using jQuery?

Learn how to easily unfollow all of your twitter followers in 3 seconds

Create Web Apps Faster With APIs

How To Create A Secure Login System With PHP And MySQL

How to create a Signup form registration

Did you find this helpful?