Question

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.

Was it helpful?

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);

OTHER TIPS

splice(start, ?deleteCount) The function is used to get one or more elements in an array and remove the selected elements from the array.

slice(?start, ?end) slice retreive selected elements without change array.

for example i have this array :

const months = ['Jan', 'March', 'April', 'June'];

let selectedElementsWithSlice = months.slice(2, 3);
//["April"]
// months = ['Jan', 'March', 'April', 'June']

let selectedElements = months.splice(2, 1); // removed from array months
//["April"]
// months = ['Jan', 'March', 'June']

For your subject you want copy element to other array.

You have a multiples solutions :

  1. for first element selected (check if contains if necessary)
array.push(months.slice(2, 3)[0]);
  1. For all elements selected
[ ... array, ... months.slice(2, 3) ]

References :

splice documentation : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

slice documentation : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top