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