skip to Main Content

I have this situation where I have to get or calculate how many characters are in multiple strings. Example:



var aText = Array(

      "There are only 2 types of people in the world:",

      "Girls and boys, any other thing? i don't know.");

There’s more than 80 characters in both strings combined. Another note is that, the strings may not be fixed as they may increase or decrease. Is there a way I can do this in JavaScript?

I tried using aText.length but this only returned how many strings where in the variable. Which in this case is only 2.

4

Answers


  1. You can use a simple forEach loop to loop through the array and get the length of each element in the array.

    However, you still need to do something with the length. In this case I’m just showing it in the console.

    I added a variable that shows the total number of characters in the array.

    var aText = Array(
    
      "There are only 2 types of people in the world:",
    
      "Girls and boys, any other thing? i don't know.");
    
    let total = 0;
    
    aText.forEach((a) => {
      console.log(a.length)
      total+=a.length;
    });
    
    console.log(total + " characters in the array");
    Login or Signup to reply.
  2. This is how I would do it.

    const array = [
        "some string of unknown length",
        "another string of some text",
        "blah blah blah"
    ]
    
    const count = (() => {
        let total = 0;
        for (const entry of array) {
            total += entry.length;
        }
        return total;
    })();
    
    Login or Signup to reply.
  3. Use String.length to get the length of each item and Array.reduce() to compute the sum of the lengths:

    const aTexts = [
      "There are only 2 types of people in the world:",
      "Girls and boys, any other thing? i don't know."
    ];
    
    const totalLen = aTexts.reduce((acc, item) => acc + item.length, 0);
    
    console.log({ totalLen });
    Login or Signup to reply.
  4. Yes, you can. To find length of characters in all strings that are inside array you can use array.join('').length

    .join(”) concatenates all the strings in the array together into a single string with no separator between them. After that .length property is used to count total number of characters in the resulting string.
    Check this example:

    const myArray = Array("A", "BB", "CCC")
    
    console.log(myArray.join("").length);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search