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
You can use map Array function:
Try map()
You can use forEach, if you want to keep the words, and the length you can do it like this:
You can then access both the size and the word in the array.
Optionally you could have a little POJO object, for easier access:
Then you can access them like:
Or using map to get the same POJO:
You could create a results object (so you have the key, "hello", and the length, 5):
The key here is to use .length property of a string:
ES6 is now widely available (2019-10-03) so for completeness — you can use the arrow operator with
.map()
or, very succinctly