Home > Software design >  How to add items to an array in this specific sequence?
How to add items to an array in this specific sequence?

Time:07-04

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

CodePudding user response:

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.

  • Related