I have an array of objects. Then I want to add another object and bind it to one that already exists in my array. This means that the index of the new object should be larger in relation to my existing object, and the remaining indices of the elements should be increased by one.
For instance:
- I have an array of 6 elements
- My new object is tied to an existing object with index = 2
- The new object enters the array with index = 3, and all objects with indexes earlier than 2 now get one place higher
I tried splitting my array into two, starting with index = 2, pushing my new element and then joining again, but my code is not working well.
for (var i in myArray) {
if (myArray[i].name === inheritedRate.inherit) {
var tempArr = [];
for (var n = i; n < myArray.length; n++) {
tempArr.push($scope.myArray[n]);
myArray.splice(n, 1);
}
myArray.push(inheritedRate);
myArray.concat(tempArr);
}
}
In other words, I have an array that looks like this:
myArray = [
{name: "not selected"},
{name: "not selected"},
{name: "selected"},
{name: "not selected"},
{name: "not selected"},
{name: "not selected"},
]
, :
myArray = [
{name: "not selected"},
{name: "not selected"},
{name: "selected"},
{name: "new element"}, // inserted
{name: "not selected"},
{name: "not selected"},
{name: "not selected"},
]