Generating random numbers from an array can be done while excluding certain specified numbers

I'm currently developing a game where players are required to choose 6 numbers between 1 and 36. My goal is to create a new array that does not include the 6 selected numbers, resulting in an array that is 30 numbers long.

Here is my approach:
The initial array is as follows:

var selectedNumbers = [2, 8, 25, 13, 8, 5]; // These are the chosen numbers
var allNumbers = [];

function prepareNumbers(){
  for (var i = 1; i <= 36; i++) {
    allNumbers.push(i);
  }
}

Although I attempted to generate the new array using the code below, it is not yet perfect as it always includes at least 1 or 2 numbers from the group of selected 6 numbers.

function generateNewNumbers() {
  let copiedAllNumbers = [...allNumbers];

  selectedNumbers.map((number) => {
    copiedAllNumbers.splice(number, 1);
  })
}

What mistake am I making in this process?

Answer №1

This approach illustrates how it can be accomplished:

clonedTotalBalls = totalBalls.filter((element) => !selectedBalls.includes(element))

When using the filter function, a predicate is applied to each element, determining whether it returns true or false. In this scenario, the predicate checks if the element is part of the selectedBalls array. Elements included in this array will result in false, while the rest will render true. It is important to note that the original array remains unchanged, as filter generates a new array.

Answer №2

splice is used to remove an element at a specific index, rather than by a specific value. To achieve the desired outcome, you can follow this approach:

function generateNewBalls() {
  let clonedTotalBalls = [...totalBalls];

  selectedBalls.map((ball) => {
    let indexToRemove = clonedTotalBalls.indexOf(ball)
    clonedTotalBalls.splice(indexToRemove, 1);
  })
}

(I also suggest considering switching from map to forEach for cases where you don't need to return a value, or exploring the use of filter and indexOf. However, this may not be directly applicable to your current question)

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

The width of Highcharts increases proportionally to the growth of the chart's width

I want to create a highcharts graph where the width increases as data points increase. Currently, I have: I am using vuejs with highcharts, but it should work similarly with jquery or other frameworks. <div class="col-md-6" style= ...

What is the reason behind not being able to utilize addEventListener on a variable that has been selected through DOM's getElementsByClassName method?

btn = document.getElementsByClassName('btn'); value = document.getElementById('value'); let counter = 0; btn[2].addEventListener('click', function() { if (btn[2].classList.contains('decrease')) counter -= 1; if ...

What is a way to activate the onSelectionChange event only when the cursor moves without any changes in the input?

In my React Native app, I have a use case where I want to implement mentions. This requires calling a function on the onSelectionChange event only when the text in the input remains unchanged but the caret position has moved. Currently, the onSelectionCha ...

Image displaying recreation of drop down lists similar to those found on Facebook pop-up windows

Seeking guidance on how to create popup drop-down lists similar to Facebook's "Who liked this link?" feature. I believe it involves the use of jQuery. Click here for an example image. Any suggestions, folks? ...

How can I retrieve JSON keys and values in JQuery and append them to a list (ul)?

Can you please review this jsFiddle link: http://jsfiddle.net/xY7tx/3108/ Whenever I use getJSON in the provided example, why does the fail part always get executed? I am seeking assistance on how to extract the key and value from the JSON file using jQu ...

Discover the best approach for transforming a complicated JSON object/array into a map using inheritance coding techniques

Could someone help me with creating an array of objects (only 1 level) based on the following JSON structure? [ { 'family' : { 'name' : 'Doe', 'from' : 'Foo' }, ...

Accessing the next and previous elements using jQuery

Aug: <input type="text" value="100000" name="targetMonth_8" id="targetMonth_8" class="targetMonth" disabled> Sep: <input type="text" value="100000" name="targetMonth_9" id="targetMonth_9" class="targetMonth" disabled> Oct: <input type="text" ...

Improving the functionality of a dynamic Mongoose JS application

Hey there, I have a pretty simple question that I couldn't find an answer to on Google. So, I'm experimenting with Mongoose JS and I'm curious about how to update a live application. Let's say I've defined a schema in my node.js ...

Utilizing D3.js to filter nodes and links by making multiple selections from a checkbox

I am interested in enhancing my current forced directed graph by adding more flexibility. You can access the Jsfiddle here. Currently, there are radio buttons that control the opacity of nodes and links. There are 4 types of nodes: Agent, Customer, Pho ...

JavaScript code encounters difficulties parsing HTML source

I'm attempting to reconstruct the WhateverOrigin service, which can be found at this link: Nevertheless, when I try running it in my web browser, this code that functioned perfectly with WhateverOrigin no longer functions properly with my imitation s ...

What is the best method for inserting the HTML content from a specific div into a textarea?

Everything seems to be working fine, but once I insert the HTML into the textarea, an issue arises where the div gets wrapped within another div, causing the layout to break. var urls = []; $('body').on('click', '.btn_video&apos ...

Error: The function named 'setValues' has already been declared

Looking for some guidance with an error message that involves the 'setValues' declaration in my code. I've come across similar questions and answers, but I'm still unsure about what changes I need to make. Your input would be highly app ...

Webpack creating a bundle file with no content

I'm currently facing a challenge with webpack/webpack-stream while trying to bundle some JavaScript files. The issue I am encountering is that, despite generating the bundle.js file, it turns out to be empty. To ensure clarity, I've provided the ...

I am facing difficulties in installing node packages using npm install

Trying to install node packages using npm, but encountering an issue. When I run the command, the output is: up to date, audited 356 packages in 7s found 0 vulnerabilities I have listed the dependencies in my package.json file like so: "dependencies& ...

Using AXIOS and VueJs to visually represent data with a two-dimensional array

I'm new to vuejs and I want to display my data response in a two-dimensional table. This is the data I have: [{ "origine": "", "nb": 15 }, { "origine": "?", "nb": 18 }, { "origine": "?L", "nb": 1 }, { "origine": "G", "nb": 298 }, { ...

Angular App Failing to Validate Session Cookie 'sessionId' in AuthGuard

Encountering a perplexing issue with my Angular application where the AuthGuard fails to recognize a session cookie named 'sessionId' correctly. I have successfully implemented user authentication, and the expected behavior is for users to be dir ...

Unable to eliminate the beforeunload event

The code below is used to display a default pop-up when the page is refreshed or closed: var myEvent = window.attachEvent || window.addEventListener; var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, ...

Discover how to initiate an ajax request from a tailored module when the page is loaded in ActiveCollab

When trying to initiate an AJAX call on the project brief page by adding a JavaScript file, I encountered some issues. My goal is to display additional information along with the existing project brief. I included a JavaScript file in a custom module and f ...

Retrieve highlighted text along with its corresponding tag in ReactJS

my <span class="highlight">highlighted</span> word The text above is showing an example including HTML tags. However, when using window.getSelection(), only the text "my highlighted word" is returned without the surrounding <span& ...

Analyzing the object for interface compatibility

When I receive a query string in one of my REST endpoints using koa-router, each value of the query string object parameter is always a string: { count: "120", result: "true", text: "ok" } Within my codebase, I have an Interface that represents the ...