Assassin eradicated from list of cast members

In my quest to select a killer from the Cast Members Array for the game, I want the function to pick one person as the killer and then remove them from the castMember player array.

Once the killer is chosen, they should be removed from the survivors array and stored separately as their own variable for future functions.

I attempted to achieve this using a for loop and splice method on the array, but unfortunately, it is not working as intended.

let episodes = 6; // Number of Episodes
let episodecount = 0; // Episode Count Value
let killer; // Initializes killer variable
let killerRevealed = false; // Initialize killerRevealed status
let stamina; // Stamina stat for each player 
let speed; // Speed stat for each player 
let strength; // Strength stat for each player 
let suspicion; // Suspicion stat for each player 
let highestPlayer; // Player with the highest stats

let castMembers = [
"Sidney Prescott",
"Gale Weathers",
"Stu Macher",
"Billy Loomis",
"Dewey Riley",
"Tatum Riley",
"Principal Himbry",
"Kenny Brown"
];

let gameStarted = false;
let objects = ["knife", "gun", "shovel", "rope", "candle", "matche", "lighter", "clothesline", "hiding spot", "clue"]; // List of objects 
let events = ["sudden outburst", "false accusation", "heated argument", "suspicious behavior", "mysterious disappearance", "surprising discovery"]; // List of random events
let scenes = ["opening scene", "house party garage scene", "outside van scene", "high school scene", "house party living room", "house party attick"]
let playAs1996Cast = document.getElementById("buttonp")
let killerSet = false;

function getRandom(arr) {
    return arr[Math.floor(Math.random() * arr.length)];
}

// Function to randomly select the Killer 
function chooseKiller(){
    
    let randomNumber = Math.floor(Math.random() * castMembers.length);
    killer = castMembers[randomNumber];

    console.log ("A new killer has been chosen: " + killer);
    
    
    for (var i = 0; i < killer.length; i++){
        if (killer[i].id == 1) {
            killer.splice(i, 1)
            break;
        }
    }

Answer №1

To remove the killer from the castMembers array, you can apply a filter function like this:

 castMembers = castMembers.filter(x => x!== killer);

It's important to note that the original array will be altered until the page is refreshed. If you want to keep the original array intact, you can create a new array instead:

 let filteredCastMembers;
 ...

 filteredCastMembers= castMembers.filter(x => x!== killer);

let episodes = 6; // Total number of episodes
let episodecount = 0; // Value count for episodes
let killer; // Initialized variable for the killer
let killerRevealed = false; // Flag for killer being revealed
let stamina; // Stamina stat for each player 
let speed; // Speed stat for each player 
let strength; // Strength stat for each player 
let suspicion; // Suspicion stat for each player 
let highestPlayer; // Player with the highest stat

let castMembers = [
"Sidney Prescott",
"Gale Weathers",
"Stu Macher",
"Billy Loomis",
"Dewey Riley",
"Tatum Riley",
"Principal Himbry",
"Kenny Brown"
];

let gameStarted = false;
let objects = ["knife", "gun", "shovel", "rope", "candle", "matche", "lighter", "clothesline", "hiding spot", "clue"]; // List of objects 
let events = ["sudden outburst", "false accusation", "heated argument", "suspicious behavior", "mysterious disappearance", "surprising discovery"]; // List of random events
let scenes = ["opening scene", "house party garage scene", "outside van scene", "high school scene", "house party living room", "house party attick"]
let playAs1996Cast = document.getElementById("buttonp")
let killerSet = false;


function getRandom(arr) {
    return arr[Math.floor(Math.random() * arr.length)];
}

// Function to randomly select the Killer 
function chooseKiller(){
    let randomNumber = Math.floor(Math.random() * castMembers.length);
    killer = castMembers[randomNumber];
    console.log ("A new killer has been chosen: " + killer);
    castMembers = castMembers.filter(x => x!== killer);
    console.log (castMembers); //gives all cast members apart from the killer
 }
 
getRandom(castMembers);
chooseKiller();//consoles all cast members apart from the killer

Answer №2

To avoid the loop, simply utilize the splice method to extract the killer from the array as it will modify the original array and return the extracted item.

Furthermore, make sure you have called the chooseKiller function in your code.

// ... set up above ...

function chooseKiller() {
  let randomNumber = Math.floor(Math.random() * castMembers.length);

  // using .pop() ensures we get the actual value as it returns an array
  killer = castMembers.splice(randomNumber, 1).pop();

  console.log(`A killer has been chosen: ${killer}`);
  console.log(`Cast members are now: ${castMembers.join(", ")}`);
}

chooseKiller();

If you prefer not to modify the original array, consider using the filter method recommended in other solutions. Preserving the original array can be advantageous if you wish to rerun the chooseKiller function without resetting the variables to their initial states.

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

Leverage the camera functionality in both native and web applications using Ionic/AngularJS and Cordova

Could you provide some guidance on how to use the Camera feature in both web and native environments? I have tried implementing it using the code snippet below, taken from ng-cordova documentation: $scope.takePicture = function() { var options ...

Development and staging setups tailored specifically for a JavaScript SDK

Currently, I am working with a Javascript SDK that is available on NPM. Alongside this, I have a Vue application utilizing the SDK and it's crucial for me to test them together across various pre-production environments (such as staging). Here are the ...

Implement a loader in AngularJS to display when transitioning between pages

Is there a way to implement a loader that appears when the page starts changing and only disappears once the entire page is fully rendered to prevent clipping bugs? I have already set up the loader as shown below: $scope.$on('$routeChangeStart' ...

Tips for utilizing multiple ngFor directives for property binding within a single directive

After implementing the ng-drag and drop npm module with the draggable directive, I encountered an issue while trying to display a list of items from a 2D array using li elements. Since multiple ngFor's are not allowed in Angular, I needed to come up w ...

Adding color dynamically to text within ion-card based on a regex pattern

My goal is to enhance the appearance of certain text elements by wrapping them in a span tag whenever a # or a @ symbol is detected, creating the look of usernames and hashtags on Twitter. Below is the code I am currently using: TS FILE: ngOnInit(): void ...

Using the data from two input fields, an ajax request is triggered to dynamically populate the jQuery autocomplete feature

I've been struggling with this issue for quite some time now. My goal is to pass 2 arguments (the values of 2 input fields in a form) in my ajax call so I can use them for a jQuery autocomplete feature (the search is based on a MySQL query using the v ...

Enhance state using the values from radio buttons in a React application

Seeking the best approach to update or set my state that stores values for radio button answers. This pertains to a personality test with 20 questions, and I aim to store all 20 answers. Each radio button input has an onChange event. My objective is to st ...

Issues with Google Analytics Event Tracker Inconsistent Performance

I am experiencing an issue with a Google Analytics event that is triggered when a user clicks on a form submission button to enroll in a course. The event uses data attributes within the button element. What's puzzling is that the event seems to be w ...

Creating a local storage file named .notification.localstore.json specific to Microsoft ConversationBot

I am in need of utilizing a ConversationBot to send messages to MS Teams users. The code snippet below was obtained from an example app generated by TeamsToolkit. It functions as expected, however, it relies on user IDs stored in .notification.localstore.j ...

Move the internal array pointer forward to the next record in order to apply the insertAfter function within the jquery code

As a new jQuery user, I'm attempting to develop a jQuery function using data provided by PHP. My goal is to arrange DIV elements in order of their values using insertAfter method. However, I seem to be encountering some difficulty in advancing the poi ...

Is there a way to retrieve both the items within a specific category and its corresponding subcategories simultaneously?

Presently, I am managing two models for Category and subcategory. The category model provides an array of data as shown below: category = [ {_id: '1', name: 'Appliances', slug: 'appliances'}, {_id: '2', na ...

Modify the numerical presentation within the provided input text

Looking to format numbers in the thousands with a comma, for example changing 2000 to 2,000 and 20000 to 20,000. While I found a solution using cleave.js library, it only works for one input field. Is there another alternative that can handle multiple in ...

Sending a JavaScript variable to PHP and retrieving the PHP result back into a JavaScript variable

I am looking to transfer a JavaScript variable to a PHP file using AJAX, and then retrieve the PHP file's output back into a JavaScript variable. For sending the JavaScript variable to the PHP file, I found a method that suggests using ajax to assign ...

Routing static pages in Angular 2

I successfully created a static page using Angular 2. When I run ng serve and visit my page, it functions as intended. Specifically, I can navigate to a specific page by typing in the URL, such as www.mysite.com/resume. However, after uploading it to my si ...

What is the best way to utilize purgeCss in conjunction with other module exports?

After reading the documentation, I want to integrate purgeCss into my NextJS project. The recommended configuration in the docs suggests updating the next.config.js file like this: module.exports = withCss(withPurgeCss()) However, I am unsure where exact ...

Creating multiple objects using a single object in JavaScript can be achieved by using the concept of object

When presented with the following data structure: { "time_1": 20, "time_2": 10, "time_3": 40, "time_4": 30 } and expecting a result in this format: [ { "key1": "time_1" ...

Unique Google Maps API V3 PEGMAN Customization

Can custom zoom controls and Pegman controls be styled with the same design? To add custom zoom controls, follow the instructions provided in this question's answer: <!DOCTYPE html> <html> <head> <meta name="viewport" cont ...

The error message "Uncaught ReferenceError: req is not defined with [email protected]" indicates that the variable

Discovered a helpful post that seems to address the problems. https://github.com/angular/angular-cli/issues/8359 I'm unsure about the steps to take next to resolve this issue. Can anyone clarify? Could you please advise on which version of Angular ...

How can we access a variable that was created within an isset($_GET[]) condition when we are inside an isset($_POST[]) condition?

For the past few days, I've been grappling with a problem that seems unsolvable to me. Within a PHP file, I have come across two if statements: The first statement retrieves the post ID from the previous page. if(isset($_GET['post'])){ ...

Error: The 'encoding' property cannot be set on null objects in THREE.js

I have been trying to load a basic grass block from Minecraft, but I keep encountering an error message that says TypeError: Cannot set properties of null (setting 'encoding'). This error originates from line 2893 in GLTFLoader, specifically the ...