I have an array of arrays.
var arr = [[1,2,3,4,5],[2,3,4,5,6],[3,4,5,6,7],[4,5,6,7,8],[5,6,7,8,9], [6,7,8,9,10], [7,8,9,10,11]];
I want to add a new item in front of and back of multiple items at specific indexes.
What I want to achieve is:
var new_arr = [["x",1,"x",2,3,4,5], [2,3,4,5,"x",6,"x"], [3,4,5,"x",6,"x",7], [4,5,"x",6,"x",7,8], [5,"x",6,"x",7,8,9], ["x",6,"x",7,8,9,10], [7,8,9,10,11]];
The issue is, when I use splice to insert a new item inside the iterated arrays, indexes does change. Because splice is a destructive function.
Here is what I tried:
var result = [];
_.each(arr, function(item, index) {
index_a = item.indexOf(1);
index_b = item.indexOf(6);
var temp_item = item.slice(0);
if(~index_a || ~index_b) {
temp_item.splice(index, 0, "x");
temp_item.splice(index + 2, 0, "x");
if(index_b > -1) {
temp_item.splice(index, 0, "x");
}
}
result.push(item);
}
During the iteration above, the first splice works just fine. But the second "x" is not placed properly. I think the reason is first splices' effect on the temp_item array. Because number of items in the array is changing.
So how can I achieve what I want? Thank you.
arris an array of arrays. Therefore,arr.indexOf(1)andarr.indexOf(6)will be-1.