convert array of letters to array of words using JavaScript
const inputArr = [ 'b', 'a', 'k', 'e', '', 'c', 'a', 'k', 'e', '', 'e', 'a', 't' ]; and my desired output is : output = ['bake','cake','eat'];
I used Join method but I am not getting desired output. const inputArr = [ 'b', 'a', 'k', 'e', '', 'c', 'a', 'k', 'e', '', 'e', 'a', 't' ];
const result=inputArr.join('');
console.log(result);
output: "bakecakeeat"
If you want the answer in different way other than Join.
You can iterate over the inputArr then keep appending the character until you found the empty space(''), there you can add the word in the outputArr and and reset the word.
const inputArr = [ 'b', 'a', 'k', 'e', '', 'c', 'a', 'k', 'e', '', 'e', 'a', 't' ];
var outputArr = [];
var word = '';
// Iterate over the array.
for (let i = 0; i < inputArr.length; i++) {
if(inputArr[i]=='') {
// If you found the empty Space(''), add to the outputArr
outputArr.push(word);
// reset the word, to start making the new word.
word = '';
// No need to execute the below code, so continue.
continue;
}
// Keep appending the character to the word.
word = word.concat(inputArr[i]);
}
// This is for the last word string.
if(word != '') {
outputArr.push(word);
}
console.log(outputArr);
You want to use
const inputArr = [ 'b', 'a', 'k', 'e', ' ', 'c', 'a', 'k', 'e', ' ', 'e', 'a', 't' ];
Note the difference between '' and ' '.
If you do not have control over the input you can change the array to fit the other answer's method:
inputArr.forEach((element, index) => {
if(element === '') {
inputArr[index] = ' ';
}
});
inputArr.join('');