-2

I have simple array look like this

[{"id":"1"},{"id":"2"},{"id":"3"}]

Also attach my array structure in image

I need to shuffle this mean i want some time second array come one first. etc

Something like this [{"id":"2"},{"id":"1"},{"id":"3"}] or on every shuffle different result come Any one can tell how is it possible ?

enter image description here

I have try this but dont know how to console the new shuffled array ?

start(CategoryID){
console.log(CategoryID);
    this.api.getQuestions(CategoryID).subscribe((data: any)=>{
      console.log(data);
      data = this.shuffle(data);

    });

}

 shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}
UmaiZ
  • 93
  • 6
  • 18
  • Does this answer your question? [How can I shuffle an array?](https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array) – Philipp Meissner Feb 12 '20 at 07:24
  • Does this answer your question? [How to randomize (shuffle) a JavaScript array?](https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array) – WorksLikeACharm Feb 12 '20 at 07:24
  • I already try with tehese questions. But its not working in my situtaion because n these question therye is only 1 array. and i have multiple array in one. – UmaiZ Feb 12 '20 at 07:44
  • @UmaiZ can you put your console after this line data = this.shuffle(data); – Venka Tesh user5397700 Feb 12 '20 at 07:59

2 Answers2

1

You can do it like this:

let array=[{"id":"1"},{"id":"2"},{"id":"3"}] 
array.sort(() => Math.random() - 0.5);

enter image description here

sacgro
  • 459
  • 2
  • 5
0

Hope it Helps!!

shufflingArray (value: any[]) {

    let items: any[] = [];

    for (let i = 0; i < value.length; i++) {
      items.push(value[i]);
    }

    // reversing items array
    for (let i = items.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [items[i], items[j]] = [items[j], items[i]];
    }
    return items;
}
Sunny Vakil
  • 362
  • 4
  • 7