0

I have an array of objects that contains Albumes and i want to shuffle it when user re-open Album's screen.

So I write some function BUT it's just got one item Not All of them, So how can i handle it to return all items after shuffle it?

Albums

"data": [
    {
      "id": 3,
      "name": "01- Out Life 2002",
      "company": "arabic rap",
      "avatar": "upload/Albums/1579652663.jpg",
      "artists_id": 3,
      "users_id": 1,
      "created_at": "2020-01-22 00:24:23",
      "updated_at": "2020-01-23 18:20:53"
    },
    {
      "id": 1,
      "name": "02 - First 2 Bomb - 2003",
      "company": "arabic rap",
      "avatar": "upload/Albums/1579803681.jpg",
      "artists_id": 3,
      "users_id": 1,
      "created_at": "2020-01-07 01:36:35",
      "updated_at": "2020-01-23 18:21:21"
    },
    {
      "id": 5,
      "name": "Scormix 1",
      "company": "arabic rap",
      "avatar": "upload/Albums/1580658846.jpeg",
      "artists_id": 4,
      "users_id": 1,
      "created_at": "2020-02-02 15:54:06",
      "updated_at": "2020-02-02 15:54:06"
    },
]

  shuffle = arr => arr[Math.floor(arr.length * Math.random())]; 

  // just return One Item ~_~
Oliver D
  • 2,579
  • 6
  • 37
  • 80
  • The current `shuffle` function only returns a random element from the array, it does not actually shuffle the array. – cbr Feb 02 '20 at 23:38

2 Answers2

1

Your function is only returning one item accessed with a random integer, but you could possibly use Array.map() to create a new array from the argument one!

Presumably you'll only want to show each album once, so I'd suggest an excellent answer to a similar question mentioning the Fisher-Yates shuffle

Simone Chiesi
  • 91
  • 1
  • 8
0

It returns exactly what it's written there: a (single) item whose index is a random number. In order to shuffle the whole array you should iterate on the items, not just returning one item. Take a look at this post here: How can I shuffle an array?

Bruno
  • 148
  • 8