I'm having a hard time wrapping my head around this one.
I have an array of objects, each object has three key/value pairs:
- index = which is simply the index number in the array.
- order = a sequential value that should always begin at 1 (basically index + 1).
- name = some text value which has no effect.
The original state of the array looks like this:
var arrayOfObjects = [
{
index:0,
order:1,
name:"Some name"
},
{
index:1,
order:2,
name:"Some other name"
}
];
I created a function to duplicate the first object in the array [0]
function duplicateObject (){
arrayOfObjects.splice(0,0,arrayOfObjects[0]);
}
Now the array looks like this -which is correct:
var arrayOfObjects = [
{
index:0,
order:1,
name:"Some name"
},
{
index:0,
order:1,
name:"Some name"
},
{
index:1,
order:2,
name:"Some other name"
}
];
I've created another function to reset/overwrite the index and order values all over, I'll call this function from within the previous function (duplicateObject):
function resetNumbers (){
for (let i=0; i < arrayOfObjects.length; i++){
arrayOfObjects[i].index = i;
arrayOfObjects[i].order = i + 1;
}
console.log(arrayOfObjects);
}
To my understanding, I should be getting:
var arrayOfObjects = [
{
index:0,
order:1,
name:"Some name"
},
{
index:1,
order:2,
name:"Some name"
},
{
index:2,
order:3,
name:"Some other name"
}
];
But what I'm actually getting:
var arrayOfObjects = [
{
index:0,
order:2,
name:"Some name"
},
{
index:0,
order:2,
name:"Some name"
},
{
index:1,
order:3,
name:"Some other name"
}
];
I don't understand why the resetNumbers function is not doing it's job. Can someone please help me understand?
Here is the entire code:
var arrayOfObjects = [{
index: 0,
order: 1,
name: "Some name"
},
{
index: 1,
order: 2,
name: "Some other name"
}
];
function resetNumbers() {
for (let i = 0; i < arrayOfObjects.length; i++) {
arrayOfObjects[i].index = i;
arrayOfObjects[i].order = i + 1;
}
console.log(arrayOfObjects);
}
function duplicateObject() {
arrayOfObjects.splice(0, 0, arrayOfObjects[0]);
resetNumbers();
}
//start the code
duplicateObject();