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

139
Vistas
I would like to fill an array with numbers using javascript with a for loop

"But I always double the numbers. so [1,1,2,2,3,3 .......] how can you do that? I am looking forward to the answer. " Continuous with a number, the for loop is good. But how do I do it with double numbers?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

To get an array to N, use:

let N = 10;
Array.from(Array(N).keys())

To double each value in any array:

[...yourArray.map(n => [n, n])].flat()

So, your solution:

let n = 10;
const a = [...Array.from(Array(n).keys()).map(k => [k, k])].flat()

console.log(a)

To have it starting from 0, not 1, alter the mapping accordingly:

let n = 10;
const a = [
  ...Array.from(Array(n).keys())
    .map(k => [k + 1, k + 1])
].flat()

console.log(a)

Arguably, the cleanest solution:

function doubleArrayTo(n) {
  const a = [];
  for (i = 1; i <= n; i++) {
    a.push(i, i);
  }
  return a;
}

console.log(doubleArrayTo(10))


Out of curiosity, I tested their performance. Unsurprisingly, the for loop wins hands down over the spread syntax:

function doubleFor(n) {
  const a = [];
  for (i = 1; i <= n; i++) {
    a.push(i, i);
  }
  return a;
}
function doubleSpread(n) {
  return [
  ...Array.from(Array(n).keys())
    .map(k => [k + 1, k + 1])
  ].flat()
}

function run_test(fn, value) {
  const t0 = performance.now();
  fn(value);
  return performance.now() - t0;
}

[1e4, 1e5, 1e6, 1e7].map(value => {
  console.log(
    `(${value}): for => ${
      run_test(doubleFor, value)
    } | spread => ${
      run_test(doubleSpread, value)
    }`);
});

about 4 years ago · Juan Pablo Isaza Denunciar

0

follow this code

var array = [];
for(int i = 0;i <= 10;i++) {
  array.push(i);
  array.push(i);//again
}

var array = [];
for (let i = 0; i <= 10; i++) {
  array.push(i,i);
}
console.log(array);

Edit

You can use multi input for array.push(i,i,i,....)

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