[SOLVED] Converting nested loops into forEach();


Im trying to learn forEach() method but i cant find more advanced examples. So i thought about refactoring my Codewars code to learn from it. I dont know know to properly use forEach method in nested loops. Hope You can help me learn from this example 🙂

6 kyu – Replace With Alphabet Position

function alphabetPosition(text) {
    let textToArray = text.replace(/[^a-zA-Z]/gi,'').toUpperCase().split(''); //Eliminate anything thats not a letter 
    const alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
    let pointsHolder = [];                            //empty array for score
    for (let i = 0; i < textToArray.length; i++){
        for  (let j = 0; j < alphabet.length; j++) {
            if (textToArray[i] == alphabet[j] ) {     //We check the index of given string letter in alphabet
                pointsHolder.push(j+1)                //give it a score based on place in alphabet(+1 for 0 as 1st index)
    return pointsHolder.join(' ');                    //return scored array as a string with spaces


(Note: @Terry’s solution is still the more efficient solution to your code challenge)

You can replace it in the following way:

function alphabetPosition(text) {
  let textToArray = text.replace(/[^a-zA-Z]/gi, '').toUpperCase().split(''); 
  const alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
  let pointsHolder = []; 
  textToArray.forEach(t2a => {
    alphabet.forEach((a, j) => {
      if (t2a == a) { pointsHolder.push(j + 1) }
  return pointsHolder.join(' '); 


Answered By – Anurag Srivastava

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published.