Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Solving a simple Javacript question using for loop and array

I am trying to solve this question using Javascript for loop and array but got stuck halfway. Need some guidance.

questions

So far what I came up with is this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const array1 = ['S','A','I','N','S'];

var text="";

for(let y = 0; y < array1.length; y++){
    text += array1[y];
    console.log(text);
}

The output are:
S
SA
SAI
SAIN
SAINS

>Solution :

I would use an array for a temporary data store. Once you get to the end of the first loop, pop off the last temp element so you don’t duplicate "SAINS", and then walk the loop backwards popping off elements until the array is empty.

const arr = ['S','A','I','N','S'];
const temp = [];

// `push` a new letter on to the temp array
// log the `joined` array
for (let i = 0; i < arr.length; i++) {
  temp.push(arr[i]);
  console.log(temp.join(''));
}

// Remove the last element
temp.pop();

// Walk backwards from the end of the temp array
// to the beginning, logging the array, and then
// popping off a new element until the array is empty
for (let i = temp.length - 1; i >= 0; i--) {
  console.log(temp.join(''));
  temp.pop();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading