Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get length of every element in array - JavaScript

I want to get length of every element in array

my code is

var a = "Hello world" ; 
var chars = a.split(' '); 

so I will have an array of

chars = ['Hello' , 'world'] ; 

but how I can get length of each word like this ?

Hello = 5 
world = 5
like image 274
HyperScripts Avatar asked Oct 28 '15 19:10

HyperScripts


2 Answers

You can use map Array function:

var lengths = chars.map(function(word){
 return word.length
}) 
like image 117
juvian Avatar answered Sep 22 '22 02:09

juvian


ES6 is now widely available (2019-10-03) so for completeness — you can use the arrow operator with .map()

var words = [ "Hello", "World", "I", "am", "here" ];
words.map(w => w.length);
> Array [ 5, 5, 1, 2, 4 ]

or, very succinctly

"Hello World I am here".split(' ').map(w => w.length)
> Array [ 5, 5, 1, 2, 4 ]
like image 39
Stephen P Avatar answered Sep 19 '22 02:09

Stephen P