Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

173
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda