0

I have this array right here

I would like to shuffly only answerA, answerB, answerC and answerD fields for each object. So I get back an array where answerA might be answerB, answerC might be answerD etc etc.

What is a simple way to do this?

nicholaswmin
  • 21,686
  • 15
  • 91
  • 167

1 Answers1

2

Using shuffleArray from https://stackoverflow.com/a/12646864/989121:

   myKeys = ['answerA','answerB','answerC','answerD']
   myValues = myKeys.map(function(k) { return myObject[k] })
   myValues = shuffleArray(myValues)
   myKeys.forEach(function(k) { myObject[k] = myValues.shift() })

That said, a simpler option would be to structure your object like this:

ID: 22
answers: [
    "first", "second answer", etc
],
category: ...
etc

Serially named variables is always an indicator that you actually need an array.

Community
  • 1
  • 1
georg
  • 211,518
  • 52
  • 313
  • 390
  • I still didn't get how the function can work with my above array. I want to keep my array as it is except for each object to shuffle only answerA-D. – nicholaswmin Jun 20 '14 at 08:07
  • @NicholasKyriakides: if you want a complete solution, post your array as javascript, or make a fiddle. – georg Jun 20 '14 at 08:09
  • Well the function would be pretty much something that gets an array as a parameter with the fields exactly as they are above, and it return an array with shuffled answersA-D. I would gladly post a JSFiddle but my array gets returned via PHP so it would be a tad hard for me to do that. – nicholaswmin Jun 20 '14 at 08:12
  • @NicholasKyriakides: in the above code, `myObject` is a single array element, to apply it to the whole array, use `myArray.forEach(function(myObject) { code })`. – georg Jun 20 '14 at 08:16
  • so considering my array is called myObject, how do I feed it in the function? I tried console.log(myArray.forEach(function(myObject)...etc) – nicholaswmin Jun 20 '14 at 08:22