Home > Blockchain >  Solving a simple Javacript question using for loop and array
Solving a simple Javacript question using for loop and array

Time:05-27

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

CodePudding user response:

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

CodePudding user response:

you can loop through the array 2times by the length of the array (y < array1.length * 2) because when you loop the entire array then you have to loop reverse to remove last character each time to have the result. you have to check if we log the entire array by y < array1.length and then with else clause we can remove the last character each time with slice(0, -1) method which removes the last character. y < array1.length * 2 - 1 the -1 is for when you reach the last character and the only character in the text string there will be nothing in the text string so it will log empty string which is not the right answer. hope I could explain well.

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

var text = "";

for (let y = 0; y < array1.length * 2 - 1; y  ) {
  if (y < array1.length) {
    text  = array1[y];
    console.log(text);
  } else {
    text = text.slice(0, -1);
    console.log(text);
  }
}

  • Related