I have a problem when i want dupplicate an object in array.
Example Array:
const fruits = [
{"name": "banana", "index": 0},
{"name": "orange", "index": 1},
{"name": "lemon", "index": 2}
];
I want to dupplicate 1 fruit and reorder their index with a function;
duplicate = (index) => {
const newList = [...fruits];
const newFruit = fruits[index];
newList.splice(index + 1, 0, newFruit);
for(let i = 0; i < newList.length; i++) {
newList[i].index = i
};
return newArray;
};
But the function "duplicate(1);" return this:
[
{"name": "banana", "index": 0},
{"name": "orange", "index": 2},
{"name": "orange", "index": 2},
{"name": "lemon", "index": 3}
]
Instead of:
[
{"name": "banana", "index": 0},
{"name": "orange", "index": 1},
{"name": "orange", "index": 2},
{"name": "lemon", "index": 3}
]
And I don't understand why ?