Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

156
Visualizações
I would like to generate a array like this [ 1, 2, ..., 9, 10 ] in javascript

if count is 4, arr will be [ 1, 2, 3, 4 ]

if count is greater than 4, arr will be like [ 1, 2, "...", 9, 10 ]

I tried this way, but output is [ 1, 2, "..." ]

const arr = [];

const count = 10;

for (let i = 0; i < count; i++) {
    if (i >= 8) {
        arr.push(i + 1);
        continue;
    }
    if (i >= 2) {
        arr.push("...");
        break;
    }

    arr.push(i + 1);
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

I'd write this as

let i=0;
for (; i < count && i < 2; i++) {
    arr.push(i + 1);
}
if (count > 4) {
    arr.push("…");
    i = count - 2;
}
for (; i < count; i++) {
    arr.push(i + 1);
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You can predefine it in the if as well and then use the loop.

let arr =

 [];
const count = 10;

if (count <= 4) {
  for (let i = 0; i < count; i++) {
    arr.push(i);
  }
} else {
  arr = [1, 2, '...', count - 1, count];
}
console.log(arr);

JSFiddle

about 4 years ago · Juan Pablo Isaza Relatório

0

From what I see from the OP's expected outputs/results it looks like the problem was more about creating kind of a sequence with ellipsis. In this case one could choose a much simpler approach.

Any sequence with a count lower than and equal to 4 will be created via Array.from and its optional mapFn parameter. For any count value which exceeds 4 there is no necessity of using any kind of loop; just create an array with the first two items which are always 1 and 2, followed by the ellipsis placeholder of '...', followed by the last two items which always have the values of count - 1 respectively count.

function createEllipsisSequence(count) {
  let list;
  if (count <= 4) {

    list = Array
      .from({ length: count }, (_, idx) => idx + 1);
      
  } else {
    list = [1, 2, '...', count - 1, count];
  }
  return list;
}

console.log('count: 3 ...',
  createEllipsisSequence(3)
);
console.log('count: 4 ...',
  createEllipsisSequence(4)
);

console.log('count: 5 ...',
  createEllipsisSequence(5)
);
console.log('count: 6 ...',
  createEllipsisSequence(6)
);

console.log('count: 10 ...',
  createEllipsisSequence(10)
);
console.log('count: 11 ...',
  createEllipsisSequence(11)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda