Roy Roy - 4 months ago 11
Javascript Question

Removing an element of an array, is removing all javascript

trying to remove an element from an array on button click
what's happening is that it seems to be removing all elements on second click?

I've edited this; what I need is for winArray to be reset winArray=[];
evrytime the button is clicked, populate it with mainSlotArr, then remove 1 element, check the console, it does it once only

This is what I've tried so far;

<!doctype html>
<html>
<head>
<meta charset="UTF-8">


<script>

mainSlotArr =["1", "2", "3", "4", "5", "6"];
var winArray =[];
var winSpin = function () {

winArray = mainSlotArr.splice(0);


var winIcon = winArray[0];

winArray = removeFromArray(winArray, winIcon);



}



function removeFromArray(array, el) {
var pos = array.indexOf(el);
pos > -1 && array.splice(pos, 1);
console.log(winArray)

}


</script>
</head>
<body>

<div>
<button type="button" onclick="winSpin();">Click Me!</button>

</div>

</body>
</html>


Thanks in advance

Roy Roy
Answer

Hi Had time to go back and look at this, the reason that the mainSlotArr and all arrays were being emptied is that I should have been using slice and not splice (That's what happens when you're working under pressure!!) Script below works as intended, really can't believe this was marked down though

<head>
    <meta charset="UTF-8">

<script>

var mainSlotArr =["1", "2", "3", "4", "5", "6"];
var mCopy =  mainSlotArr.slice();
var firstTime = true;
var winArray = [];


var winSpin = function () {

 winArray =  mCopy.slice();

console.log(winArray)

var winIcon = winArray[0];

winArray = removeFromArray(winArray, winIcon);



}



function removeFromArray(arr, el) {
   var pos = arr.indexOf(el);
   pos > -1 && arr.splice(pos, 1);
   mCopy =  winArray.slice();

}


    </script>
</head>
<body>

 <div>
    <button type="button" onclick="winSpin();">Click Me!</button>              

</div>

</body>
</html>