0

It just all of a suddenly crossed my mind we all know using regular for loop and push() method to convert string characters into an array

let myStr = "Perseverance";
let emptyArr = [];

for (let i = 0; i < myStr.length; i++) {
    emptyArr.push(myStr[i]);
}
console.log(emptyArr); 

then I decided to convert a whole string into a single element of an array just using push()...worked

let myStr = "Perseverance powers";
let emptyArr = [];

for (let i = 0; i < myStr.split().length; i++) {
  emptyArr.push(myStr);
}
console.log(emptyArr);

Now here when I want to separate each word into a single element of an array just using push() I can't... Here is my question: How can I convert each word of the string into a single element of an array using only push() and for loop

P.S. A lot ways exist yet it was just a thought came to my mind 'what if' Thanks

Durdona A.
  • 310
  • 3
  • 15

1 Answers1

1

You can use JavaScript's split to create an array of words.

const myStr = "Perseverance powers";
const arr = myStr.split(' ');
console.log(arr);

documentation for split

Here's what I came up with if you want to do this using push

const str = 'Perseverance powers';
const arr = [];
let temp = '';

str.split('').forEach(character => {
    if(character === ' ') {
    arr.push(temp);
    temp = '';
  } else {
    temp += character;
  }
})
arr.push(temp);

console.log(arr)
ahsan
  • 1,409
  • 8
  • 11