Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 🙂

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading