I have an array of objects similar to:
[
{
number: 1,
name: "A"
},
{
number: 2,
name: "e",
},
{
number: 3,
name: "EE",
}
]
I need to be able to insert an object to the array at a particular position, but then I have to shift all the numbers of rest of the object, so the numbers are in sequence order. Similarly I need to be able to remove an object, but be able to shift all the numbers back.
i.e. If I insert at location 1 with name: "F", the array became:
[
{
number: 1,
name: "A"
},
{
number: 2,
name: "F"
},
{
number: 3,
name: "e",
},
{
number: 4,
name: "EE",
}
]
I know a few ways that can do it, but none of them looks pretty. Post some of my thoughts here:
- To insert I did
this.arr.splice(1, 0, newObj)
, then tried to loop through this.arr, for any index greater than 2, I did ++number, this works, but ugly. - To insert I did
this.arr.splice(1, 0, newObj)
, then split this.arr withlet newArr = this.arr.split(2)
, thennewArr.map(a => {...})
, use splice to replace part of original arr with newArr.
New Edit: Share some of my code here, this works, but I'd like to simply it or make it prettier if possible. Please share thoughts.
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)
}