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:

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();
}

Leave a Reply