The program has to put all the letters together but it is not working. I've tried with the debugger but does not show any errors. The code:
var phrase = [ 'h', 'e', 'l', 'l', 'o',' ', 'w', 'o', 'r', 'l', 'd' ];
let sentence: string[] = createSentence(phrase);
sentence.forEach(letter => {
console.log(letter);
});
function createSentence(letters: string[]): string[]
{
var add = "";
var result: string[] = [];
phrase.forEach(unionL => {
if (unionL != ' ') {
add = unionL;
} else {
result.push(add);
add = "";
}
});
return result;
}
CodePudding user response:
It's not pulling the entire array because of the condition you have used in your array. You need to add one more condition for the last chunk to be added to the result array. Here is the code:
function createSentence(letters: string[]): string[]
{
var add = "";
var result: string[] = [];
phrase.forEach((unionL,index) => {
if (unionL != ' ') {
add = unionL;
} else {
result.push(add);
add = "";
}
//New Code
if(index===phrase.length-1){
result.push(add);
}
});
return result;
}
Another way is to keep your code and just add an empty string at the end of the string that will work with your logic. Example:
var phrase = [ 'h', 'e', 'l', 'l', ' ', 'w', 'o', 'r', 'l', 'd', ' ' ];