Search code examples
javascriptarrayspushsplice

JavaScript splice and place into another array


I'm currently making a game which requires me to take an object from an array and place it into another array.

a = obj;
array1.splice(a);
array2.push(a);

(a is already in array1)

This is pretty much what I need to happen.

I'm not an expert so please explain your answer in depth.


Solution

  • Javascript Array Splice() Method works as following...

    array.splice(index,howmany)

    It takes index number of the item to remove, how many items to remove as it's parameter and these two are required.

    For more you can follow this link : http://www.w3schools.com/jsref/jsref_splice.asp

    So, your problem can be solved as following...

    a = obj;
    var index = array1.indexOf(a);
    array1.splice(index,1);
    array2.push(a);