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

174
Vistas
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 Respuestas
Responde la pregunta

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