Tess Tess - 3 months ago 18
TypeScript Question

Typescript -dynamically add id to array and sort

I have a pre-rendered array of agenda items to which a user can add items and also type in what position in the agenda the item should have.

The array in the constructor:

this.agendaItems = [{
id: 1,
subject: 'Opening of the meeting'
}, {
id: 2,
subject: 'Election of chairman'
}, {
id: 3,
subject: 'Approval of the agenda'
}, {
id: 4,
subject: 'Presentation of the annual report and audit report'
}, {
id: 5,
subject: 'Adjurnement of the meeting'
},
];


And the method for pushing the agendaItem to the array:

saveAgendaItem(num: number, subj: string) {
var item = {id: num, subject : subj}
this.agendaItems.push(item);
}


This works but here is my problem: Lets say the user want to add a new item to position 4 (id). I need to:


  1. Sort and the display the items in order by id.

  2. Push the previous item no 4 to position 5 and also

  3. Re-write the id's for all the items that comes after the new item.



I'm not sure how to achieve this in typescript.

Any ideas?

Answer

In principle, changing an 'id' is not a good idea. If ID represents just the position, then maybe you don't need it.

Anyway, regarding the object insertion, you may need to use splice (See How to insert an item into an array at a specific index?)

It would be something like: this.agendaItems.splice(4, 0, item)

Regarding the renumeration, I would suggest to traverse with a for loop all the items from the desired position to the last item, changing the 'id'.