Array shift()

Hi, I have an array of many valor and each element is shifted, so i think this array is empty…I need to shit() this array but i won’t leave the valor. If you understand me, can you suggest to me something?

Thanks.

Can you show us code that demonstrates the problem?

Hi, Paul Wilkins see you again.

ok this is my code:

``````//function random array

function knuthShuffle(arr) {

var rand, temp, i;

for (i = arr.length - 1; i >= 0; i--) {
rand = Math.floor((i + 1) * Math.random()); //get random between zero and i (inclusive)
temp = arr[rand]; //swap i and the zero-indexed number
arr[rand] = arr[i];
arr[i] = temp;
}
return arr;
}

var x =  knuthShuffle(carte); // x is array random generate from array carte.

// I have another array 'scarti'

// button function
function dealCards(){
if(x.length > 0){carta1.innerHTML = "<img src='cards/" + x.shift() + "' />"; scarti.push(x.shift);}
}

// now another function. Button for shuffle the array, i think to report in original array carte, but i can't.
function shuffle(){
var i = 0;
while(i<scarti.length){
carte.push(scarti.shift());
}
i++;
}
``````

I think the code is ok but i can’t shuffle the deck how to create original deck, somebody can help me?Thank you.

I have posted the code but I have no answare…sorry somebody can help me?

Where is the array `carte` declared? I can see it being used, but not where it’s initialised. Is that the full code you’ve posted?

no it’s not the full code, you can help me? array carte is what you want…and the code is ok but i can’t shuffle the array.
…first step: random array, second step display the array.shift() third step: report to array at the origins…
I am stoppet in third step…you know that I mean? Thank you.

It definitely helps if you post all of the code that is relevant to the problem. Can you add the missing piece(s) in? It’s probably too late to edit post #3 now, so if you add it to your next post, that will be fine.

PS. That would include the section of HTML you’re working with.

this is the complete code…before you try, you have to change the tag img

``````<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title></title>
<style>
body{background-color:green;}
.casella img{width:100px;}
.btng{margin-top:20px;}
.rigacheckbox td{text-align:center;}
</style>
</head>
<body>
<center style="margin-top:50px;">
<form name="uno">
<table>
<tr>
<td class="casella" id="carta1"><img src="cards/dorso carte.png" /></td>
<td class="casella" id="carta2"><img src="cards/dorso carte.png" /></td>
<td class="casella" id="carta3"><img src="cards/dorso carte.png" /></td>
<td class="casella" id="carta4"><img src="cards/dorso carte.png" /></td>
<td class="casella" id="carta5"><img src="cards/dorso carte.png" /></td>
</tr>

<tr class="rigacheckbox">
<td><input type="checkbox" name="check1"></td>
<td><input type="checkbox" name="check2"></td>
<td><input type="checkbox" name="check3"></td>
<td><input type="checkbox" name="check4"></td>
<td><input type="checkbox" name="check5"></td>

</tr></table> </form>
<div class="btng">
<button id="btn" onclick="handler()">DAI CARTE</button>
<button id="btn2" onclick="ScartiHandler()">SCARTA</button>
<button id="btn3" onclick="mischiaHandler()">MISCHIA</button>
</div>
<p>Carte: <span id="v">52</span> - scarti: <span id="d">0</span> - Valore: <span id="f"></span></p>
</center>

<script>

var carte = new Array();

carte[0] = "Asso di Cuori.png";
carte[1] = "Asso di Quadri.png";
carte[2] = "Asso di Fiori.png";
carte[3] = "Asso di Picche.png";
carte[4] = "Due di Cuori.png";
carte[5] = "Due di Quadri.png";
carte[6] = "Due di Fiori.png";
carte[7] = "Due di Picche.png";
carte[8] = "Tre di Cuori.png";
carte[9] = "Tre di Quadri.png";
carte[10] = "Tre di Fiori.png";
carte[11] = "Tre di Picche.png";
/*
carte[12] = "4c";
carte[13] = "4q";
carte[14] = "4f";
carte[15] = "4p";
carte[16] = "5c";
carte[17] = "5q";
carte[18] = "5f";
carte[19] = "5p";
carte[20] = "6c";
carte[21] = "6q";
carte[22] = "6f";
carte[23] = "6p";
carte[24] = "7c";
carte[25] = "7q";
carte[26] = "7f";
carte[27] = "7p";
carte[28] = "8c";
carte[29] = "8q";
carte[30] = "8f";
carte[31] = "8p";
carte[32] = "9c";
carte[33] = "9q";
carte[34] = "9f";
carte[35] = "9p";
carte[36] = "10c";
carte[37] = "10q";
carte[38] = "10f";
carte[39] = "10p";
carte[40] = "Jc";
carte[41] = "Jq";
carte[42] = "Jf";
carte[43] = "Jp";
carte[44] = "Qc";
carte[45] = "Qq";
carte[46] = "Qf";
carte[47] = "Qp";
carte[48] = "Kc";
carte[49] = "Kq";
carte[50] = "Kf";
carte[51] = "Kp";
*/

var carta1 = document.getElementById("carta1");
var carta2 = document.getElementById("carta2");
var carta3 = document.getElementById("carta3");
var carta4 = document.getElementById("carta4");
var carta5 = document.getElementById("carta5");

var val = document.getElementById("f");

// funzione che randomizza le carte

function knuthShuffle(arr) {

var rand, temp, i;

for (i = arr.length - 1; i >= 0; i--) {
rand = Math.floor((i + 1) * Math.random()); //get random between zero and i (inclusive)
temp = arr[rand]; //swap i and the zero-indexed number
arr[rand] = arr[i];
arr[i] = temp;
}
return arr;
}

var x =  knuthShuffle(carte);
var scarti = [];

//scrivo funzioni per recuperare le query

function showDeck(arg){
document.querySelector("#v").innerHTML = arg.length;
}

function showDiscards(arg){
document.querySelector("#d").innerHTML = arg.length;
}

// funzioni delle carte

function dealCards() {

if(x.length > 0){carta1.innerHTML = "<img src='cards/" + x.shift() + "' />"; scarti.push(x.shift);}
if(x.length > 0){carta2.innerHTML = "<img src='cards/" + x.shift() + "' />"; scarti.push(x.shift);}
if(x.length > 0){carta3.innerHTML = "<img src='cards/" + x.shift() + "' />"; scarti.push(x.shift);}
if(x.length > 0){carta4.innerHTML = "<img src='cards/" + x.shift() + "' />"; scarti.push(x.shift);}
if(x.length > 0){carta5.innerHTML = "<img src='cards/" + x.shift() + "' />"; scarti.push(x.shift);}

}

function scarta(){
// scartare carte

if(x.length > 0){

if(document.uno.check1.checked == true){carta1.innerHTML = "<img src='cards/" + x.shift() + "' />"; scarti.push(x.shift);}
if(document.uno.check2.checked == true){carta2.innerHTML = "<img src='cards/" + x.shift() + "' />"; scarti.push(x.shift);}
if(document.uno.check3.checked == true){carta3.innerHTML = "<img src='cards/" + x.shift() + "' />"; scarti.push(x.shift);}
if(document.uno.check4.checked == true){carta4.innerHTML = "<img src='cards/" + x.shift() + "' />"; scarti.push(x.shift);}
if(document.uno.check5.checked == true){carta5.innerHTML = "<img src='cards/" + x.shift() + "' />"; scarti.push(x.shift);}

}

}

function mischia(){

carta1.innerHTML = "<img src='cards/dorso carte.png' />";
carta2.innerHTML = "<img src='cards/dorso carte.png' />";
carta3.innerHTML = "<img src='cards/dorso carte.png' />";
carta4.innerHTML = "<img src='cards/dorso carte.png' />";
carta5.innerHTML = "<img src='cards/dorso carte.png' />";

}

function shuffleDeck(deck) {
return knuthShuffle(deck);
}

//Handler

function handler(){
dealCards();
showDeck(x);
showDiscards(scarti);
}

function ScartiHandler(evt) {
scarta();
showDeck(x);
showDiscards(scarti);
}

function mischiaHandler(){
while(scarti.length > 0){
x.push(scarti.shift());
}
x = shuffleDeck(x);
mischia();
showDeck(x);
showDiscards(scarti);
}

</script>

</body>
</html>
``````

type or paste code here

The `.shift()` method modifies the original array; if you just want the first element of an array (the head) as well as an array containing the remaining elements (the tail), this can be done like

``````var head = carte[0]
var tail = carte.slice(1)

// Or using ES6 syntax
let [head, ...tail] = carte
``````

BTW, your `knuthShuffle()` function also modifies the array it receives; it would be much better to create a copy of `arr` first, and then shuffle and return that copy, leaving the original array untouched:

``````function knuthShuffle (arr) {
var res = arr.slice()
var rand
var temp
var i

for (i = res.length - 1; i >= 0; i--) {
rand = Math.floor((i + 1) * Math.random())
temp = res[rand]
res[rand] = res[i]
res[i] = temp
}

return res
}

// Now x contains the shuffled array, while
// carte is still in its original order
var x = knuthShuffle(carte)
``````

i have remove the tag img and to change the knuthshuffle function but the error is function shift() native code…

you can show me an example in my code? why I can’t…thank you.

somebody can help me? You give me this code:

``````var head = carte[0];
var tail = carte.slice(1);
``````

you can help me how to insert this variable??? Please follow previus code.

The gist is not to modify the original array; instead, try to write pure functions that take some input and return some output without producing side effects. Note that objects like arrays are always passed by reference though, so you’ll have to take special care not to modify the arguments; you can always create a copy with the `.slice()` method though.

For example, your `shuffle()` function (which also has another bug BTW since `i` never increments) could be rewritten like

``````function shuffle (carte, scarti) {
var newCarte = carte.slice()
var i

for (i in scarti) {
newCarte.push(scarti[i])
}

return newCarte
}
``````

Confusingly, there are some array methods that do modify the array they are called on (such as `.push()` and `.shift()`) and some that don’t but return a new array instead (such as `.slice()` and `.concat()`). In case of doubt, check out the API at the MDN. Speaking of `.concat()`, if all the above function does is append one array to the other, you might just write

``````var newCarte = carte.concat(scarti)
``````

There are certainly occasions where side effects are necessary, most notably when you have some sort of state (such as keeping track of the cards in a game). I’d suggest to keep your functions pure wherever possible though, or do such modifications within the scope of a function which is itself pure; it makes your code much easier to reason about.

1 Like

sorry but I don’t understand…

I am start whit shift() method and now you give me a splice method…I am confused.

P.S could I use the shift and push method for deal and reloaded the deck…??? What do you suggest?

please show me the right way…

If I understand you correctly, you want to keep the original array. The `.shift()` method however modifies the array it is called on, even if that array got passed to a function. Consider

``````function getFirst (arr) {
return arr.shift()
}

var myArray = [1, 2, 3]
var first = getFirst(myArray)

console.log(first)   // 1
console.log(myArray) // [2, 3]
``````

So if you want to keep the original array, you’ll have to create a copy. This can be achieved with the `.slice()` method (not to be confuced with `.splice()`, which does modify the array):

``````function getFirst (arr) {
var copy = arr.slice()
return copy.shift()
}

var myArray = [1, 2, 3]
var first = getFirst(myArray)

console.log(first)   // 1
console.log(myArray) // [1, 2, 3]
``````

Another possibility is of course not to modify the array at all:

``````function getFirst (arr) {
return arr[0]
}

var myArray = [1, 2, 3]
var first = getFirst(myArray)

console.log(first)   // 1
console.log(myArray) // [1, 2, 3]
``````

This example function is of course not particularly useful. In the case of your `shuffle()` function, you could iterate over the array in question instead of `.shift()`ing it in a `while` loop. Please see my previous post.

Probably. I would suggest to solve the current issue at hand before considering further modifications of your code, though.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.