Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!