8

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

6 Answers 6

9

You can use map Array function:

var lengths = chars.map(function(word){
 return word.length
}) 
Sign up to request clarification or add additional context in comments.

Comments

6

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 ]

4 Comments

Or you can do it with array comprehension: [for (word of words) word.length]
@friedi - nice also! but MDN warns "Non-standard. Do not use!" ... this was removed from the ES6 draft; it could conceivably end up in ES7, and MDN compatibility chart shows only Firefox currently supports it. Still cool.
I'm lost! OK, so "words" is an array, and "words.map" gets the length of each word, which it stored in an array as "> Array[5,5,1,2,4]. But how to access the cells of that latter array? What is it's name?
@Cristofayre - in my answer the examples are from typing in the browser console, and I'm not assigning the result of words.map to anything. You would want to do something like let wordLengths = words.map(w => w.length); then you an access the latter array as wordLengths[i] just like any other array. In the browser console I use var but in actual js code I never use it; I use const and let.
3

The key here is to use .length property of a string:

   for (var i=0;i<chars.length;i++){
    console.log(chars[i].length);
    }

Comments

2

You could create a results object (so you have the key, "hello", and the length, 5):

function getLengthOfWords(str) {
    var results = {}; 
    var chars = str.split(' ');
    chars.forEach(function(item) {
        results[item] = item.length;
    });
    return results;
}

getLengthOfWords("Hello world"); // {'hello': 5, 'world': 5}

Comments

2

Try map()

var words = ['Hello', 'world'];

var lengths = words.map(function(word) {
  return word + ' = ' + word.length;
});

console.log(lengths);

Comments

1

You can use forEach, if you want to keep the words, and the length you can do it like this:

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

    var words = [];
    chars.forEach(function(str) { 
        words.push([str, str.length]);
    });

You can then access both the size and the word in the array.

Optionally you could have a little POJO object, for easier access:

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

var words = [];
chars.forEach(function(str) { 
    words.push({word: str, length: str.length});
});

Then you can access them like:

console.log(words[0].length); //5
console.log(words[0].word); //"Hello"

Or using map to get the same POJO:

var words = chars.map(function(str) { 
    return {word: str, length: str.length};
});

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.