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 https://www.codewars.com/kata/546f922b54af40e1e90001da/train/javascript
JavaScript
x
14
14
1
function alphabetPosition(text) {
2
let textToArray = text.replace(/[^a-zA-Z]/gi,'').toUpperCase().split(''); //Eliminate anything thats not a letter
3
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"];
4
let pointsHolder = []; //empty array for score
5
for (let i = 0; i < textToArray.length; i++){
6
for (let j = 0; j < alphabet.length; j++) {
7
if (textToArray[i] == alphabet[j] ) { //We check the index of given string letter in alphabet
8
pointsHolder.push(j+1) //give it a score based on place in alphabet(+1 for 0 as 1st index)
9
}
10
}
11
}
12
return pointsHolder.join(' '); //return scored array as a string with spaces
13
}
14
Advertisement
Answer
(Note: @Terry’s solution is still the more efficient solution to your code challenge)
You can replace it in the following way:
JavaScript
1
13
13
1
function alphabetPosition(text) {
2
let textToArray = text.replace(/[^a-zA-Z]/gi, '').toUpperCase().split('');
3
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"];
4
let pointsHolder = [];
5
textToArray.forEach(t2a => {
6
alphabet.forEach((a, j) => {
7
if (t2a == a) { pointsHolder.push(j + 1) }
8
})
9
})
10
return pointsHolder.join(' ');
11
}
12
13
console.log(alphabetPosition("ABCSTU"))