Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!