Frage

How can I remove an object from a copy of an array without removing it from the original?

I have a global variable :

    var userTrickList = [];

And inside a function, I make a copy of that global array :

    var tempUserTrickList = userTrickList;

Then I use the removeItem function that I created to remove a certain object.

    removeItem(considerTrick.IDName, tempUserTrickList);


    function removeItem(item, list) {
        //takes a string as 'item', finds in the array as 'list', 
        //then removes it from the list.
        for(var i = 0; i < list.length; i++)
        {
            if(item === list[i])
            {
                list.splice(i,1);
            }
        }
    }

My problem is, this function removes it from the userTrickList too.

Any ideas? It's definitely a problem in "removeItem(considerTrick.IDName, tempUserTrickList);", but I can't think of a solution.

War es hilfreich?

Lösung

Use .slice(0) to clone an array.

var tempUserTrickList = userTrickList.slice(0);

Credits: http://davidwalsh.name/javascript-clone-array

Andere Tipps

use this function for your requirement

function removeElementFromArray(data,target) {
var temp=new Array();   
for ( var i = 0; i < data.length; i++) {
    if(data[i]!=target){
        temp.push(data[i]);
    }
}
return temp; }

here data is original array and target is the element you want to remove from array this function will return array without containing the removed item.

Try, It copy the original array

var tempUserTrickList = JSON.parse(JSON.stringify(userTrickList));

Demo CopyArray

for (i = 0, l = arr.length; i < l; i++) {
  if (arr[i] === item) {
    arr.splice(i, 1);
    i -= 1;
    l -= 1;
  }
}

Daniel's method of cloning an array is absolutely correct, but since I don't see an ES6-oriented answer, I'll offer up an alternative solution:

We can just as easily use the spread operator to clone an array, so we don't have to use the slice call.

const arr = [1, 2, 3];
const copy = [...arr];
copy.pop();
console.log(arr);  // returns [1, 2, 3]
console.log(copy); // returns [1, 2]
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top