Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove an item from a copy of an array without removing it from the original array

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.

like image 599
Daniel Archer Avatar asked Dec 03 '22 19:12

Daniel Archer


1 Answers

Use .slice(0) to clone an array.

var tempUserTrickList = userTrickList.slice(0);

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

like image 70
Daniel Avatar answered Dec 22 '22 07:12

Daniel