skip to Main Content

Im a very beginner.

I need to write down for an array list the array and then the number of characters that array concists of.

example

apple 5
banana 6
grapefruit 10

I have trouble to count the characters of one array.
I only know to count the list of arrays, ie. in this example 3.

It needs to be a loop.
So for I have this

const fruit = ["apple", "banana", "grapefruit"];

let fruitCountChar = 0;    
   for (let i = 0; i < fruit.length; i++) {    
      fruitCountChar = fruit.length;
      console.log(fruit[i], fruitCountChar);
} 

3

Answers


  1. You already managed to successfully log the fruit names to console, all you need to do now, is access the length property of the exact same thing:

    const fruit = ["apple", "banana", "grapefruit"];
    
    let fruitCountChar = 0;    
       for (let i = 0; i < fruit.length; i++) {    
          fruitCountChar = fruit[i].length;
                             // ^^^
          console.log(fruit[i], fruitCountChar);
    } 
    Login or Signup to reply.
  2. As i understand your requirement.
    you can use this:

    function displayLength(arr) {
    let result = '';
    for (let i = 0; i < arr.length; i++) {
        result += `${arr[i]} ${arr[i].length} `;
    }
    return result.trim();
    }
    
    Login or Signup to reply.
  3. You could change the loop to for..of since you don’t need the index:

    const fruits = ["apple", "banana", "grapefruit"];
    
    let fruitCountChar = 0;    
       for (const fruit of fruits) {    
          fruitCountChar = fruit.length;
          console.log(fruit, fruitCountChar);
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search