Home  >  Q&A  >  body text

A function that capitalizes the first three letters of each word in the given array.

<p>I wrote a function that takes a word and capitalizes the first three letters. Now I need to run the same function on an array of words to return the first three letters of each word in upper case. I see a lot of people asking how to capitalize the first letter of every word in a sentence, but it's not the same thing. I have to use a function I've already written so that when I print it using console.log, its output looks like this: </p> <pre class="brush:php;toolbar:false;">console.log(applyAll(['str1', 'str2', 'str3', 'str4'], capitalizeThreeLetters));</pre> <p>I tried using a for loop to achieve this, but it returned the result of all the words concatenated. In my research I saw that you can use the forEach() method to run a function on array elements, but I can't figure out how to apply it. </p> <pre class="brush:php;toolbar:false;">//Function that takes in str returns it with three first letters capitalized function capitalizeThreeLetters(str){ let capFirst = str[0].toUpperCase(); let capSecond = str[1].toUpperCase(); let capThird = str[2].toUpperCase(); let splitStr = str.slice(3); let wholeStr = capFirst capSecond capThird splitStr; return wholeStr; } console.log(capitalizeThreeLetters('testing')); // => returns 'TESting' console.log(capitalizeThreeLetters('again')); // => returns 'AGAin' //Function that takes in a string array and applies capitalizeThreeLetters function to each array element so each word is returned with first three letters capitalized function applyAll(arr){ for (let i = 0; i < arr.length; i ){ return capitalizeThreeLetters(arr); } } console.log(applyAll(['mai', 'brian', 'jeho', 'han'], capitalizeThreeLetters)); // => returns 'MAIBRIANJEHOhan' // => should return ['MAI', 'BRIan', 'JEHo', 'HAN']</pre> <p><br /></p>
P粉899950720P粉899950720472 days ago489

reply all(1)I'll reply

  • P粉331849987

    P粉3318499872023-07-30 00:31:04

    Your applyAll function doesn't work the way you want. When you return, the function exits immediately. In this case, you're returning inside the loop, preventing the loop from continuing and running the other two iterations.

    Your second problem is that you are passing the entire array to capitalizeThreeLetters, not a single word. You may want to use capitalizeThreeLetters(arr[i]). Now, you're passing the entire array, causing the first three words in the array to be capitalized, rather than the first three letters of each word.

    You can use the map method to fix it:

    function applyAll(arr){
      return arr.map(capitalizeThreeLetters);
    }
    

    Using the map function on an array will call a function on each element of the array and return a new array containing the result.

    reply
    0
  • Cancelreply