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

177
Visualizações
How to add items to an array in this specific sequence?

I need to follow the certain pattern:

Examples below are just examples, but in practice the array could be any size for e.g 100 items long and any item can be removed for e.g the 55th out of 100.

Add first item:

const items = [1]

Add second item:

const items = [1, 2]

Remove second item (2 in this case):

const items = [1]

Add third item

const items = [1, 3]

So in other words, everytime I add an item it should tally up by 1.

But when I remove an item from the array, and then add a new item I need to remember what the previous number which was was added and add 1 to it.

Another example:

const items = [3, 4]

Add an item:

const items = [3, 4, 5]

Remove the first item (3 in this case):

const items = [4, 5]

Add a new item:

const items = [4, 5, 6]

Thanks :)

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You'll have to keep track of the count using a variable, and then use that variable each time you append to your array (making sure to also increment it each time):

let count = 1;
const items = [];

const appendAndIncrementCount = () => {
  items.push(count);
  count += 1;
};

const log = () => console.log(JSON.stringify(items));

// "add first item"
appendAndIncrementCount();
log(); // [1]

// "add second item"
appendAndIncrementCount();
log(); // [1,2]

// "remove second item"
items.splice(1, 1);
log(); // [1]

// "add third item"
appendAndIncrementCount();
log(); // [1,3]

// ...etc.

Note that, instead of using a closure, you can also simply array.push(count++);, but I used the closure to illustrate that you can customize the functionality of your operation.

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