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

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"];

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

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

>Solution :

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