1

I have a list of words and instructions that I need tied together but I would like to present their order randomly. For example, say I have (cat, forget) (dog, remember) (turtle, forget) where the first part is the word and the second part is the instruction. The word should always be followed by the instruction that it's attached to, but the words themselves should be presented randomly. So it would be okay if the order was (dog, remember) (turtle, forget) (cat, remember) as long as "dog" is always attached to "remember" etc.

How would I best represent this? Should it be an array of arrays where the "sub-array" is the (dog, remember) pair??

Thanks!

ManoDestra
  • 6,325
  • 6
  • 26
  • 50
user5826447
  • 357
  • 1
  • 5
  • 13
  • 3
    See [How to randomize (shuffle) a JavaScript array?](http://stackoverflow.com/q/2450954/1529630) – Oriol Jul 15 '16 at 14:48

3 Answers3

2

That's simple. You need to have an array of objects, where each object has 2 properties - "word" and "instruction".

var data = [
  {
    "word": "Cat",
    "instruction": "forgets"
  },
  {
    "word": "Man",
    "instruction": "remembers"
  }
];
Mohit Bhardwaj
  • 9,650
  • 3
  • 37
  • 64
  • Theres 2 parts to the question: -_but the words themselves should be presented randomly_. – BenG Jul 15 '16 at 14:48
  • 1
    @BenG That part is a dupe of [How to randomize (shuffle) a JavaScript array?](http://stackoverflow.com/q/2450954/1529630), so it's not worth answering. – Oriol Jul 15 '16 at 14:49
  • @user5826447 That's an object, a plain javascript object. – Mohit Bhardwaj Jul 15 '16 at 14:51
1

You could create a javascript custom object and then an array of those objects.

function MyData(word,instruction) {
    this.word=word;
    this.instruction=instruction;
}

var arr = [new MyData("dog","forget"), new MyData("turtle","forget")];

To randomize the output you will need to rearrange the array with a loop. As mentioned in the comments.

Rick S
  • 6,476
  • 5
  • 29
  • 43
1

Here is a solution using a javascript array of objects and a Fisher-Yates shuffle (https://bost.ocks.org/mike/shuffle/)

function shuffle(array) {
  var m = array.length,
    t, i;

  // While there remain elements to shuffle...
  while (m) {

    // Pick a remaining element...
    i = Math.floor(Math.random() * m--);

    // And swap it with the current element.
    t = array[m];
    array[m] = array[i];
    array[i] = t;
  }

  return array;
}

var words = [{
  word: "cat",
  instruction: "forget"
}, {
  word: "dog",
  instruction: "remember"
}, {
  word: "turtle",
  instruction: "forget"
}];

var shuffledWords = shuffle(words);

var targetDiv = document.getElementById('target');

shuffledWords.forEach(function(word) {
  targetDiv.innerHTML = targetDiv.innerHTML + word.word + ", " + word.instruction + "<br />";
});
<div id="target"></div>
Zack
  • 2,789
  • 33
  • 60