Ways to eliminate a particular character from an array using JavaScript

What is the best way to remove a specific number from an array in this scenario? There are 9 numbers stored in the array named nums and an empty array called narr. The goal is to randomly select an index (let's call it rand) from nums, remove that number from nums, and add it to narr. I have tried using methods like pop, splice, slice but none of them seem to give the correct answer. Can you suggest the most effective method?

function sudoku(arr){
  let nums = [1,2,3,4,5,6,7,8,9];
  let narr = [];
  for(let i = 0; i<9; i++){
    let rand = Math.floor(Math.random()*nums.length);
    narr.push(nums[rand]);
    nums.pop(nums[rand]);    
  }
  return narr; 
}

Answer №1

It is recommended to utilize the splice() method in order to delete an element from an array. While pop() deletes the last element, if you need to eliminate an element at a specific index such as rand, then splice() is the way to go.

The first parameter of splice() indicates the index from which you wish to remove the element, while the second parameter represents the number of elements to be removed.

nums.splice(rand, 1);   

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

Unable to activate function when closing Vuetify v-alert

Is there a way to trigger a function when the Vuetify v-alert is closed? I have explored the documentation but haven't found any information on this specific functionality. In the codepen example, the dismissible attribute allows for closing the alert ...

Implement Material-UI Higher Order Components in a Class-based Component

I'm in the process of incorporating material UI into my class component rather than converting everything to Hooks. I'm unsure which approach would be simpler, utilizing Hooks or adapting what I currently have. https://material-ui.com/styles/bas ...

Tracking locations in real time with the AR.js framework

Is it possible to utilize the AR.js web framework for creating an Augmented Reality web app that helps users navigate from their current location to a specific destination with coordinates (lat, long)? I am looking to have it compatible with Chrome/Safari ...

What is the best way to apply a class to a button in Angular when clicking on

Creating a simple directive with two buttons. Able to detect click events on the buttons, but now looking to add a custom class upon clicking. There is a predefined class: .red { background-color: red; } The goal is to dynamically apply this class whe ...

I'm perplexed by the inner workings of infinite ajax scroll in fetching additional posts

As someone who is new to JavaScript, I find it challenging to grasp the concept, especially when incorporating it with HTML. Despite this, I decided to experiment with infinite ajax scroll functionality. Below is my code snippet: var ias = jQuery.ias({ ...

Program does not display the expected alert message when using if/else statement

I'm grappling with creating a basic program that accomplishes the following: Develop a function declaration named changePowerTotal which accepts: The total current power generated (a numeric value) A generator ID (a number) The new status of ...

Can you explain the exact purpose of npm install --legacy-peer-deps? When would it be advisable to use this command, and what are some potential scenarios where it

Encountered a new error today: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a1cfc4d9d5d5d6c8cfe1918f908f91">[em ...

Launching a Bootstrap modal in Portrait mode through JavaScript

Is there a way to trigger the opening of a modal when the screen is in "Portrait" orientation and hide it when the screen is in "Landscape" orientation? I have tried implementing this functionality, but it seems to not work properly when the page initiall ...

Develop a versatile JavaScript or jQuery script that automatically sets the focus on the first input field within a div or tag when the user clicks on it

I am currently working on creating a data entry form using a table layout. The form has two columns - the first column for input titles and the second column mostly for input tags. I styled the inputs in the second column to appear transparent with no bord ...

How to remove an item from localStorage using a loop in AngularJS

I am struggling to figure out how to delete an element in localStorage within a loop. In the save method, I add elements and check for duplicates. Can you please explain how I can delete an element using only the id or all values? My Factory .factory(&ap ...

Issue with table sorting functionality following relocation of code across pages

I had a working code that I was transferring from one webpage to another along with the CSS and JS files, but now it's not functioning properly. <head> <link type="text/css" rel="stylesheet" href="{{ STATIC_URL }}assets/css/style.css"> ...

Creating entries in ListView

I am trying to create a listview using data from an array This is my XAML: <Page.Resources> <DataTemplate x:Key="IconTextDataTemplate"> <StackPanel Orientation="Horizontal" Width="220" Height="60"> &l ...

Referencing a JavaScript source in the vendor file in Rails 4: Tips and Tricks

After realizing that my GMaps for Rails setup needs amendment, I've decided to insert javascript files directly into my app. Rails 4 - Gmaps4Rails - map won't render I've downloaded the infobox and markerclusterer repositories and now find ...

Please ensure to provide a boolean value when using wrapper.setChecked() in Vue Test Utils

Working on a project with Vue, I have implemented some radio inputs: <label> <input v-model="myProperty" v-bind:value="true" name="myProperty" type="radio" > True </label> <label> <inpu ...

Discord Server Boost Tracker Bot - Monitor Your Boosts!

Can anyone assist me in setting up a function to send a notification whenever someone boosts the server? Below is an example of the code I have so far. Any help would be greatly appreciated! bot.on('guildMemberUpdate', (oldMember, newMember) => ...

What steps should I take to move the content to the bottom of the page once the promise is fulfilled within the function?

I have a showBoxConfirm function that confirms user actions. After clicking the button, it triggers the clickMethod function. The result variable will store the confirmation response, and if it returns false, the function will terminate. However, the sho ...

Steps to execute a download function in jQuery for retrieving an audio file

I am facing a challenge in creating a download button that should, upon clicking, locate the URL of the current playing song and initiate the download process. However, pressing the button currently opens the file location instead of downloading it. I am a ...

Tips for emphasizing keywords within anchor text

I am faced with an HTML document that is filled with anchors, each having text and a href link. Just to give you an idea, here is how they are structured: <a href="URL_GOES_HERE"> Some Clickable Text Goes Here </a> My goal is to develop a sni ...

Problem with JQuery when iterating over Form components

I am currently working on a form validation function that loops through all the elements in a form. The goal is to keep the submit button disabled if any element is empty (the button is initially disabled), and enable it only when all input values are fill ...

Traverse an SVG element using JavaScript

I have a beautiful star SVG that I created, and I want to use it instead of styling a span to create floating bubbles in my div. However, I'm facing some challenges in adapting my Javascript loop to incorporate the SVG for creating the bubbles, as opp ...