Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return an array of numbers that represent lengths of elements string?

If an array was: [‘hey’, ‘you’, ‘muddy’]
The expected output should be: [3, 3, 5]

This is what I have so far:

function lengths(arr) {
  numbersArray = [];
  for (var i = 0; i < arr.length; i++) {
    numbersArray = arr[i].length;
  }
}

Any help would be much appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to push the length of every item (using Array#push) and return the array in the end:

function lengths(arr) {
  const numbersArray = [];
  for (let i = 0; i < arr.length; i++) {
    numbersArray.push(arr[i].length);
  }
  return numbersArray;
}

console.log( lengths(['hey', 'you', 'muddy']) );

Another solution using Array#map:

function lengths(arr) {
 return arr.map(str => str.length);
}

console.log( lengths(['hey', 'you', 'muddy']) );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading