I have an array of objects that looks like this:
[
{
number: 1,
name: "A"
},
{
number: 2,
name: "e",
},
{
number: 3,
name: "EE",
}
]
I am looking for a way to insert an object into the array at a specific position and then adjust the numbers of the rest of the objects so they are in sequential order. Similarly, I need to be able to remove an object and shift the numbers back accordingly.
For example, if I insert at position 1 with name: "F", the array would become:
[
{
number: 1,
name: "A"
},
{
number: 2,
name: "F"
},
{
number: 3,
name: "e",
},
{
number: 4,
name: "EE",
}
]
I have come up with some solutions, but I'm not entirely satisfied with them. Here are a few thoughts:
- I tried using
this.arr.splice(1, 0, newObj)
to insert, followed by looping through the array to increment the numbers where necessary. It works, but it's not elegant. - Another approach was to splice the array, create a new array excluding the inserted element, and then use splice again to replace part of the original array with the new one.
Here is a snippet of my code that achieves the desired outcome, but I'm open to suggestions on how to simplify or improve it:
const newObj = {
number: obj.number + 1,
name: 'S',
}
this.arr.splice(obj.number, 0, newObj)
if (this.arr.length > obj.number) {
const remaining = this.arr.slice(obj.number + 1).map( (t) => ({...t, ...{number: t.number + 1}}))
this.arr.splice(newObj.number, remaining.length, ...remaining)
}