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

268
Vistas
In Javascript how do I create a secondary array in a specific index?

How do I create a subarray from an existing array in Javascript?

For example;

Arr = [5,2,1,2]

Then I want to insert 8 in position 1 of Arr, but keep the original value 2. So arr can become:

Arr = [5,[2,8],1,2]

I tried using concat, which sort of did something but duplicates all values.

Bear in mind that this can grow e.g. Arr = [5,[2,8,3,4],1,[2,3]]

Thanks!

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

0

You could assign the concatinated values.

const
    addAt = (array, value, index) => array[index] = [].concat(array[index], value),
    array = [5, 2, 1, 2];

addAt(array, 8, 1);
console.log(array)

addAt(array, 3, 1);
console.log(array)
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Denunciar

0

There are several different ways to do this, but you can reassign the current array index to an array like so:

Arr[1] = [Arr[1], 8]. Then if you wanted to continue adding to the array at index 1 in Arr, you could do something like Arr[1].push(x).

about 4 years ago · Juan Pablo Isaza Denunciar

0

You could do something like this (Probably not the best answer, but may be helpful)

const addIntoArray = (arr, toAdd, index) => {
  arr[index] = typeof arr[index] == "number" ? [arr[index], toAdd] : [...arr[index], toAdd];
  return arr
}

Arr = [5,2,1,2]

console.log(Arr); // [ 5, 2, 1, 2 ]
addIntoArray(Arr, 1, 1)
console.log(Arr); // [ 5, [ 2, 1 ], 1, 2 ]
addIntoArray(Arr, 3, 1)
console.log(Arr) // [ 5, [ 2, 1, 3 ], 1, 2 ]

Basically ...arr expands the array and then we add toAdd at it's end and [arr[index], toAdd] creates an array with the first element as the number and the second the new element. (It modifies the original array, as shown in the example, so pay attention as it may lead to bugs)

The typeof arr[index] == "number"is just a simple/generic typecheck to see if there isn't an array already

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