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

178
Views
How to get these patern using for loop

I wanted to create a for loop that would make a pattern like this.

* two tree four five
one * tree four five
one two * four five
one two tree * five
one two tree four *

* * tree four five
one * * four five
one two * * five
one two tree * *

* * * four five
one * * * five
one two * * *

* * * * five
one * * * *

* * * * *

The problem is the array length can change anytime from

const temp = ["one","two","three","four","five"];

to

const temp = ["one","two","three","four"]; or const temp = ["one","two","three"];

This is what I got so far

        const temp = ["one","two","three","four","five"];
        
        
        let arrayResult = [];

        for(let y=0;y<temp.length;y++){
            let tempArr = temp.slice();
            tempArr[x] = "*";           
            arrayResult.push(tempArr);
        }


console.log(arrayResult);

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

0

You are almost there. Just have to use 2 loops for creating the whole pattern.

const temp = ["one","two","three","four","five"];
let arrayResult = []
for(let i = 0; i< temp.length; i++){
    for(let j = 0; j< temp.length - i; j++){
        let tempArr = temp.slice();
        let stars = Array(i+1).fill('*')
        tempArr.splice(j, i+1, ...stars);
        arrayResult.push(tempArr);
    }}

Upvote if it helped :)

about 4 years ago · Juan Pablo Isaza Report

0

Another approach using flatMap and reduce.

const data = ["one", "two", "three", "four", "five"];

const output = data.flatMap((_, i, arr) =>
    arr.reduce((carry, _, idx) => {
        if (idx < arr.length - i) {
            const temp = arr.slice();
            for (let j = 0; j < i + 1; j++) {
                temp[idx + j] = "*";
            }
            carry.push(temp);
        }
        return carry;
    }, [])
);

console.log(output);

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!