Remove items from an array in a random order until it is completely emptied

My goal is to choose a random element from an Array and then remove it, repeating this process until the Array is empty.

I have experimented with the .filter() function and Math.random without success. I also attempted to implement it within a for loop, but none of my attempts were fruitful.

Answer №1

let weekdays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'];
const index = Math.floor(Math.random() * weekdays.length);
console.log(weekdays[index]); //displays the random day

let selectedDay = weekdays[index]
weekdays = weekdays.filter(function(day) {
  return day !== selectedDay
})

console.log(weekdays); //prints the array after removing the selected day

Answer №2

If you want to get a random element from an array, you can generate a random index each time and use the Array#splice method.

const arr = [1, 2, 3, 4];
function getRandomElement(){
  return arr.splice(Math.random() * arr.length | 0, 1)[0];
}
console.log(getRandomElement());
console.log(arr);

However, for your specific use case, it might be more efficient to shuffle the array and then iterate through it. The Fisher-Yates shuffle algorithm is one way to achieve this.

const arr = [1, 2, 3, 4];
for(let i = arr.length - 1; i > 0; i--){
  const j = Math.random() * (i + 1) | 0;
  [arr[i], arr[j]] = [arr[j], arr[i]];
}
for(const element of arr) console.log(element);

Answer №3

The use of .filter() results in the creation of a fresh array rather than altering the original one.

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

Tips for formatting dates in Angular 6

I am currently working on a function that displays real-time dates based on user input. Currently, when the user enters the input, it is displayed in the front end as follows: 28.10.2018 10:09 However, I would like the date to change dynamically based on ...

The edit functionality in jqGrid does not function properly if custom search parameters are designated

Using the Guriddo jqGrid JS version 5.2.0 implemented here: @license Guriddo jqGrid JS - v5.2.0 - 2016-11-27 Copyright(c) 2008, Tony Tomov, [email protected] The code block below showcases an entire self-contained implementation of jqGrid. It inclu ...

Is there a way to transform an argument into a string in bash scripting?

After running the script with a single argument, I aim to store that argument into a variable and access it as individual characters. For example, if I input $ ./script foo, I should be able to access each letter separately. Therefore, echo $pass[0] would ...

Challenges with ColdFusion's floating point calculations

I am encountering an issue with my program where it is not displaying two decimal points properly. For example, when I enter 140.00, it shows as 140.0. Strangely, if I enter 140.15, it displays correctly as 140.15. It seems to consistently drop the zero. B ...

Using Vue.js to dynamically toggle CSS classes based on data using a method

Here is the code snippet I am working with: <template> <div id="projects"> <Header /> <b-container> <div class="row"> <div :class="colSize" v-for="(data, index) in projects" :key="data._id"> <b- ...

Ensure Rxjs waits for the completion of the previous interval request before moving forward

Scenario: It is required to make an API call every 3 minutes to update the status of a specific service within the application. Here is my existing code snippet: interval(180000) .subscribe(() => this.doRequest ...

Retrieving information from a JSON file using AngularJS

Hello, I am a beginner in Angularjs and I am facing an issue while trying to retrieve data from a JSON file. The output I am getting is quite strange. Below are snippets from my controller.js and services.js files: angular .module('app') .contro ...

Issue with the gulp-babel plugin: Files within the Plugin/Preset should only export functions, not objects

I have started to integrate JavaScript 2015 (ES6) into my Ionic v1 app: package.json { "name": "test", "version": "1.0.0", "dependencies": { "@ionic-native/deeplinks": "^4.18.0", "cordova-android": "7.0.0", "cordova-android-support-gra ...

Immediate add/modify

Exploring various websites online, I've come across platforms that offer the ability to manipulate data effortlessly. From inserting records to deleting and editing them, the process seems seamless. What's intriguing is how, upon clicking the r ...

Set default selected value for dropdown list using radio buttons

Could anyone provide guidance on how to reset a dropdown list value using a radio button selection? Specifically, I need the dropdown list to reset to its default "selected" option when a particular radio button is clicked. Any recommended approaches usin ...

What are the available events offered by Express websockets?

I am interested in learning about the different websocket events available. Currently, I have only used the ws.on('message') event, but I would like to find out how to detect when the connection is established and closed. I attempted to add the w ...

Struggling with implementing React routing in version 4.0

Struggling to route multiple pages using BrowserRouter in Reactv4. Many online guides are outdated and not working with the latest version. Here is my setup: Index.js: import React from 'react'; import ReactDOM from 'react-dom'; impo ...

"Customized color selection based on conditions using Angular's UI-Grid

I'm trying to create conditional coloring in my grid based on the data, using the cellClass function in columnDefs. The issue I'm facing is that the classes are not updated when there is a selection change, preventing me from defining colors for ...

Issue with Ionic and Angular: Struggling to empty input field

Within my Ionic app, there is a form that contains an input field and a button. Upon clicking the button, an action should occur within the controller to clear the input field. Unfortunately, this functionality is not working as expected. Despite its simpl ...

Is the Ajax DataType response JSON showing as "OK" but the output is blank?

So, I'm facing a challenge here. I have a basic jQuery Ajax request that isn't working when I set the DataType to "JSON". var form_data = { "id": msg, "token": token }; $.ajax({ type: 'POST', url: "ajax.php", ...

Tips for utilizing rest parameters in JavaScript/Typescript: Passing them as individual parameters to subsequent functions, rather than as an array

Question about Typescript/JavaScript. I made my own custom log() function that allows me to toggle logging on and off. Currently, I am using a simple console.log(). Here is the code: log(message: any): void { console.log(message) } Recently, I decid ...

Unexpected results occurring during JavaScript refactoring process

Having this repetitive code snippet that switches between two radio buttons being checked within my $(document).ready(): $(document).ready(function () { $("#New").click(function () { var toggleOn = $("#New"); var tog ...

Using Angular, we can assign an array iteration as the value for a dropdown option in

Following the controller logic: $scope.form_data = { day: 'Day' }; $scope.days = [ 'Day',1,2,3,4,5,6,7,8,9,10, 11,12,13,14,15,16,17,18,19,20, 21,22,23,24,25,26,27,28,29,30, 31 ]; In the html section: <select n ...

Temporarily withhold the execution of useEffect until useSelector successfully fetches data from the Redux store within a React

I have a functional React component called Tasks_1. Initially, I retrieve the userId from the Redux store, which is working successfully. After obtaining the userId from the Redux store, I want to use it in a useEffect hook to fetch data from the backend. ...

Sort through various table columns

I am currently utilizing a data table component from Framework7, which is being generated dynamically with JSON data. My goal is to make the column filter input functional within the table. So far, I have succeeded in implementing the filter for the first ...