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

266
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 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