Friday 18 March 2016

javascript change elements in array




I have an array of objects. Then I want to add another object and stick it to the one that already existed in my array. Which means the index of the new object should be larger by one in relation to my already existed object and rest of the element's indexes should be incremented by one.



For example:





  1. I have array of 6 elements

  2. My new object is stick to existed object with index = 2

  3. New Object enters into an array with index = 3 and all objects with indexes previously greater then 2 now get one place higher



I tried to split my array into two starting from index = 2, push my new element, and then join and again but my code do not work 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 which looks like this:



myArray = [
{name: "not selected"},
{name: "not selected"},
{name: "selected"},
{name: "not selected"},

{name: "not selected"},
{name: "not selected"},
]


And I want to put there an external element to make it look this:



myArray = [
{name: "not selected"},
{name: "not selected"},

{name: "selected"},
{name: "new element"}, // inserted
{name: "not selected"},
{name: "not selected"},
{name: "not selected"},
]

Answer



If I understood you right, the problem for you is to how to insert and move elements in array. You can do it with splice method, which has optional parameters for elements to insert:




Here is what you need for your example:





var myArray = [
{name: "not selected"},
{name: "not selected"},
{name: "selected"},
{name: "not selected"},
{name: "not selected"},

{name: "not selected"}
];

myArray.splice(3, 0, {
name: "new element"
});
console.log(myArray);





No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...