I have been trying to learn javascript for a year now, and have just embarked on HackerRank's 30 days of code. After a couple of days I finally solved this problem. Here is the task (if you click the link, press x to the signup page):
Task
Given a string S of length N that is indexed from 0 to N-1, print its even-indexed and odd-indexed characters as space-separated strings on a single line (see the Sample below for more detail).
Sample Input
2
Hacker
RankSample Output
Hce akr
Rn ak
Here is my solution. Any performance optimizations I could make here?:
function processData(input) {
//Enter your code here
//split the string into an array
let words = input.split("\n").slice(1),
odd = "",
even = "",
newStr = "";
//turn each string inside the array into its own array
let wordsArr = words.map((val) => {
return val.split("");
})
//outer loop for the outer array
for (let i = 0, len = wordsArr.length; i < len; i++){
//inner loop for the inner arrays
for (let j = 0, len2 = wordsArr[i].length; j < len2; j++){
//if the index is even or odd, add to the respective strings
if (j % 2 === 0){
even += wordsArr[i][j]
} else if (j % 2 !== 0) {
odd += wordsArr[i][j];
}
//if the end of the array is detected, print the string
//and set odd/even strings to be blank for the next iteration
if (j == len2 - 1){
newStr = `${even} ${odd}`;
even = "";
odd = "";
console.log(newStr);
}
}
}
}