Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I shuffle a JavaScript array?

I am trying to randomize the order of my array in my Angular6 project. I have no idea how to do it and ended up trying to sort the array with the Math.random() function... (didn't work XD)

This is my code so far:

HTML

    <div style="background: darkcyan; width: 600px; height: 600px; margin: auto">
  <table>
    <tr *ngFor="let card of cards">
      <div id="{{card.id}}" [ngStyle]="{'background-color': card.color}" style=" width: 100px; height: 125px; margin: 5px"></div>
    </tr>
  </table>
</div>
<button (click)="shuffle()">Shuffle Cards</button>

TypeScript

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-memory-game',
  templateUrl: './memory-game.component.html',
  styleUrls: ['./memory-game.component.css']
})
export class MemoryGameComponent implements OnInit {
  cards = [];
  constructor() { }

  ngOnInit() {
    this.cards = [
        {
          'id': 1,
          'color': 'red'
        },
        {
            'id': 2,
            'color': 'green'
        },
        {
            'id': 3,
            'color': 'blue'
        },
        {
            'id': 4,
            'color': 'yellow'
        }
    ];
      this.shuffle();
  }

  public shuffle() {
      this.cards.sort(Math.random);
  }
}

I don't know if there is an easy solution, but I really hope someone is able to help me out..

Thanks

like image 582
Marcus Scharf Avatar asked Aug 26 '26 19:08

Marcus Scharf


1 Answers

I think the problem is that you need to do something like:

this.cards.sort((a,b) => 0.5 - Math.random());

based on some previous answers on SE

Or do something like this:

 this.cards.sort(() => Math.random() - 0.5);

Based on this SE Query


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!