5

I want to shuffle an array in the typescript

images:Symbols[] =
[this.seven,this.bell,this.watermelon,this.plum,this.lemon,this.cherry];

how can i shuffle it? Here images is the name of my array and symbols is the data type of the array.

shagi.G
  • 121
  • 1
  • 2
  • 10
  • what do you mean by shuffle? – Niladri Jan 03 '18 at 18:46
  • This isn't a typescript specific problem since they type of your array is irrelevant to the shuffling operation. Take a look at [this question.](https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array) – CRice Jan 03 '18 at 18:47
  • i want to change the places of the object in the array each time – shagi.G Jan 03 '18 at 18:49
  • this is also applicable to other types of array so it's a generic question and there is already some solution available for this – Niladri Jan 03 '18 at 18:53
  • https://basarat.gitbooks.io/algorithms/content/docs/shuffling.html – Ray Hulha Dec 09 '18 at 10:38
  • 1
    I'm not sure why this question is closed, its a typescript question, the solution using one line is: this.images.sort((a,b)=> Math.random() -0.5); – Ateik Mar 03 '20 at 13:50
  • 1
    When next voting whether to keep this closed, I ask you to scroll through the link where the answer is apparently and tell me how many answers you have to scroll to find the TS one, This question totally warrants having a separate TS version that doesn't get lost in the sea of its JS counterparts – Max Carroll Jul 04 '22 at 20:07

1 Answers1

10

Similar to as javascript array.

But you would need to specify the types of the parameters and also a return type. Yes you could configure your setup to not care about these things, but then that would defeat the object of using typescript.

export function shuffle<T>(array: T[]): T[] {
    let currentIndex = array.length,  randomIndex;

    // While there remain elements to shuffle.
    while (currentIndex != 0) {
  
      // Pick a remaining element.
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex--;
  
      // And swap it with the current element.
      [array[currentIndex], array[randomIndex]] = [
        array[randomIndex], array[currentIndex]];
    }
  
    return array;
};

You can get different options of shuffle from this question.

Max Carroll
  • 4,441
  • 2
  • 31
  • 31
Sergii Rudenko
  • 2,603
  • 1
  • 22
  • 24