Array shuffled randomly

I need to connect a list of words with corresponding instructions, but I want the order of the words to be random. For example, if I have pairs like (cat, forget) and (dog, remember), the word should always be followed by its matching instruction, but the actual order of the words should be mixed up. So, for instance, it could be presented as (dog, remember) (turtle, forget) (cat, remember) as long as each word is correctly paired with its instruction.

What would be the best way to organize this? Should I use an array of arrays where each sub-array represents a pair like (dog, remember)?

Appreciate any guidance on this!

Answer №1

To accomplish this task, create an array of objects with two key-value pairs each - "term" and "direction".

var wordsList = [
  {
    "term": "Dog",
    "direction": "barks"
  },
  {
    "term": "Woman",
    "direction": "laughs"
  }
];

Answer №2

If you want to create a custom JavaScript object, start by defining the properties of the object and then store multiple instances of that object in an array.

function CustomObject(value1, value2) {
    this.value1 = value1;
    this.value2 = value2;
}

var objectsArray = [new CustomObject("apple", "eat"), new CustomObject("banana", "peel")];

To shuffle the output randomly, you can write a function to rearrange the elements in the array using a loop as mentioned in the comments above.

Answer №3

Check out this code snippet that demonstrates how to use a JavaScript array of objects along with a Fisher-Yates shuffle algorithm for randomizing elements.

function shuffleArray(array) {
  var length = array.length,
    temp, index;

  while (length) {
    index = Math.floor(Math.random() * length--);
    temp = array[length];
    array[length] = array[index];
    array[index] = temp;
  }

  return array;
}

var items = [{
  item: "apple",
  category: "fruit"
}, {
  item: "banana",
  category: "fruit"
}, {
  item: "carrot",
  category: "vegetable"
}];

var shuffledItems = shuffleArray(items);

var outputDiv = document.getElementById('output');

shuffledItems.forEach(function(item) {
  outputDiv.innerHTML = outputDiv.innerHTML + item.item + ", " + item.category + "<br />";
});
<div id="output"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for transferring information from a Ruby controller to an application JavaScript using AJAX?

When clicking a button, an AJAX call is made in my application.js file. It sends 3 data points to the events_controller#check action: //application.js $(document).on('click', "#check-button", function(){ ... $.ajax({ ...

Displaying Google Picker results in an error due to an invalid origin value

After utilizing the same code for a period of 2 years, we are encountering an issue where the picker no longer displays. I have consulted resources on Google Picker API Invalid origin but haven't been able to successfully set the origin value. The cod ...

ng-model in html input with a name of "foo[]"

Apologies for the lack of a more specific title. In HTML, when we need multiple values for a given name, we utilize the name="foo[]" attribute. Upon posting the data, it arrives as an array. I am seeking this same functionality with ng-model in Angular. ...

Issues with Angular toggle sorting functionality not functioning as expected

$scope.searchObject = { from: 0, hydrate: false, size: 12, sort: 'timestamp:desc' }; $scope.sort = function(a) { var ascend = a + ':' + 'asc'; var descend = a + ':' + 'desc'; if ($scope.searc ...

Using jQuery, how can you make fixed elements fade as the page scrolls?

How can I make a fixed element, such as a corner ad or notice, fade when the page is scrolled down to a certain point? What would be the most effective method for determining this point: using pixels, percentage, or another way? And how can I implement th ...

performing asynchronous operations with async functions within the array.map() method in JavaScript

My goal is to loop through an array of elements, check if a theme exists for each element using the "findOne()" function, and if not, create a new theme, save it, and make some changes. If the theme already exists, I just need to apply some changes and the ...

Verify if a <select> element exists inside the main div

Is there a way for me to check if a <select> element is present within the parent div and display certain content based on its existence? Appreciate any assistance! ...

Encountering an Issue with NextJS on GAE: EROFS Error indicating a read-only file system

Trying to deploy a customized Next.js application into Google App Engine has hit a snag. The project runs smoothly locally and on Google Cloud Platform CLI, but upon successful deployment using gcloud app deploy, an error arises when opening the app. 2020 ...

Implement a horizontal scrollbar for your table in HTML

I need to implement a horizontal scroll bar for my table. Here is the HTML code: Even though I have utilized Bootstrap, the horizontal scroll bar is not working for this particular module. It works fine in other modules. The tbody data is added after an ...

Monitor changes in the DOM using AngularJS

In my project, I have a form that is initially hidden using ng-if to remove it from the DOM. Later on, I show the form and attempt to submit the button within it using the following code: <form action="post.php" ng-if="success == true" method="post"&g ...

What is the best way to set the source of an image using JavaScript

On a recent project, I came across this function in PHP: foreach ($reports["included_reports"] as $index => $report_name ) { if (! in_array( $report_name, $reports["excluded_reports"])) { $optional_reports .= "<div class=\"la ...

The PHP script failed to display accurate information on the server terminal

I am looking to execute the following script: <?php $file = file_get_contents('data.json'); echo ($file); unset($file); exit(0); ?> When I access this script via ajax in JavaScript, everything works fine. However, when I ...

Changing the position of the icon in the bootstrap validator

I'm currently attempting to validate form fields in a web project. The goal is to achieve a specific result, similar to the image below: https://i.stack.imgur.com/EVeJf.png While I have made progress with a simple solution that almost meets the requi ...

How can one get rid of a sudden strong beginning?

Recently, I delved into the world of CSS animation and encountered a frustrating issue. I've tried numerous methods and workarounds to achieve a smoothly looping animation without interruptions. Despite my efforts, I have not been able to replicate th ...

`Is there a way for Javascript to retrieve information sent from Python Flask's render_template() method?`

Issue: I am facing difficulties in retrieving and displaying the data that I send from Javascript code when the user visits the site's landing page. The data in question is a dataframe. Backend Python Code: from flask import Flask, render_template, ...

Having trouble choosing options within Material UI's Autocomplete Component?

I'm having trouble selecting the options displayed in MUI's autocomplete component. It seems that using renderOption is causing this issue. I want to show an image along with the title in the component options, but without using renderOption, I h ...

Utilize the appendTo() function and make a switch to dynamically insert content stored in variables into a specified

I am working on developing a page with a central content div, where users have the ability to choose various options that will introduce different additional content. This added content will then present more opportunities for adding new elements, ultimate ...

The functionality of Next.JS Cpanel Deployment Server.js appears to be malfunctioning

Trying to deploy my website on cpanel, I am utilizing a node.js application with cpanel. Here is the configuration: https://i.sstatic.net/AXap3.png However, when I start my server, it displays "503 service unavailable." https://i.sstatic.net/17JAu.png ...

Employing the html.validationmessagefor to display a client-side error notification

My text fields have server-side validation messages. The field 'title' is a required field on the server side with a '[Required]' data attribute in the class, but it only seems to be checked on a postback or form submit. I am saving the ...

Having trouble with implementing image resizing and cropping in a Node.js environment

Struggling with image processing in node js, this task is crucial for my application. The goal is clear: 1) User uploads an image (multipart formdata sent to the server - successful) 2) Resize the image to a max width of 640px 3) Crop the picture within s ...