gamer gamer - 5 months ago 9
Javascript Question

javascript add and remove multiple value from a list in and from specific index

I have a code like:

var data = ["apple", "ball", "cat", "dog", "elephant", "fish", "gorilla"]
var index = [1, 3] // ball and dog
var to = 5 // fish

for(var i in index){
console.log(index[i])
var local_data = data
data.splice(to, 0, data.splice(index[i]), 1)
}

console.log(data)
console.log(index)


JsFiddle

Here
var index = [1,3]
is the index value of the data to be set.

What I want here is, to set the value of
index
i. e
ball
and
dog
after
fish
and the rest remains on the order.

After inserted I want the
index
value to be changed according to the new position of the
ball
and
dog
i. e
[4, 5]


Updata

In the end I want the result like:
console.log(data)
should give

["apple", "cat", "elephant", "fish", "ball", "dog", "gorilla"]


and
console.log(index)
should give:

[4, 5] // new value of ball and dog

Answer

you can do it in this way.

var data = ["apple", "ball", "cat", "dog", "elephant", "fish", "gorilla"]
var index = [2, 3] // ball and dog
var to = 5 // fish

var arrTemp = [];

data.forEach(function(val,key){

  if(index.indexOf(key)!=-1){

    data.splice((to+1),0,data[key]);
    to++;
    delete data[key];

  }
})
data = data.filter(function(val){ return val != undefined }); 

console.log(data)

JsFiddle