Having trouble obtaining and removing the index of a string in an array in JavaScript

As a newcomer to the world of Javascript, I am currently working on creating a memory game. However, I seem to be encountering some issues with getting this particular piece of code to function correctly. My goal is to select a random element from my ids array, remove it from the array, and then use that value to assign it to an element in the cards array. The code snippet I have come up with so far (updated version) looks like this:

const cards = document.querySelectorAll(".memory-card");

let ids = ["1", "1", "2", "2", "3", "3", "4", "4", "5", "5", "6", "6"];

function idHandler() {
    let rand = Math.floor(Math.random() * ids.length);
    let x = ids.splice(rand, 1)[0];
    cards[x].setAttribute("id", x);
}

cards.forEach(mapIds);

In response to a request for HTML elements:

<div class="memory-card" id="1">
    <img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="1">
    <img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="2">
    <img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="2">
    <img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="3">
    <img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="3">
    <img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="4">
    <img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="4">
    <img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="5">
    <img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="5">
    <img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="6">
     <img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="6">
     <img src="../assets/turned.png" class="front-face">
</div>

Answer №1

Make sure to access the array correctly,

function idHandler() {
    let rand = Math.floor(Math.random() * ids.length);
    let x = ids[rand]
    ids.splice(rand,1) // You can remove an index from the array this way
    cards[rand].setAttribute("id", x); // The values are already strings since they are stored with "" marks
}

To simplify the process, you can eliminate the variable x if not needed

function idHandler() {
    let rand = Math.floor(Math.random() * ids.length);
    cards[rand].setAttribute("id", ids[rand]); // The values are already strings as they are stored with "" marks
    ids.splice(rand,1) // You can use this to remove an index from the array
}

Answer №2

Allow me to assist you in comprehending your current code and identifying the errors within it:

You don't actually need ids.indexOf(rand) in this part of the code, because Math.Random generates a number between 0 and 1, which is then multiplied by ids.length. This means that the value of Math.random() will range from 0 to the length of ids. Since the array is zero-based, you can directly use this value as a parameter for the function used to split the array.

    let rand = Math.floor(Math.random() * ids.length); 
    let x = ids.indexOf(rand.toString()); 

The Array.prototype.pop( ) method always removes the last element of an array and returns its value. Therefore, you are consistently obtaining the last element in this scenario.

    ids.pop(ids[x]); 

An alternative solution would be to utilize Array.prototype.splice(). This particular function requires two arguments - start index and end index - and modifies the original array while also returning the removed element in a new array.

I have included a code snippet below for your reference. It would be beneficial to run this code in your own IDE, implement console.log( ) to track values at each stage, and gain a better understanding of the process. If you have any questions, please feel free to ask in the comments section below.

let ids = ["1", "1", "2", "2", "3", "3", "4", "4", "5", "5", "6", "6"];

function idHandler() {
    const rand = Math.floor(Math.random() * ids.length);
    const x = ids.splice(rand, 1)[0]; 
    //[0] added above to return the removed element instead of an array 
    //that contains the element
    console.log(x);
    console.log(ids);
}

idHandler();

Answer №3

One way to accomplish your goal is by using the splice method like this:

const items = document.querySelectorAll(".item");

let numbers = [1, 2, 3, 4, 5];

function randomizeNumbers() {
    let index = Math.floor(Math.random() * numbers.length);
    let removedNumber = numbers.splice(index, 1);
}

items.forEach(updateNumbers);

The splice() function removes elements from an array at a specified position and returns those elements as a new array.

To learn more, you can visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

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

Issue with padding in Material UI button component not being applied as expected

I am struggling with applying padding and styles to my Material UI component. Take a look at the code snippet below: import "./css/Landing.css"; import { Button } from "@mui/material"; function Landing() { return ( <div class ...

Tips for sorting ng-Table using an array of numerous values

I am currently working on implementing angular-selectize.js (https://github.com/machineboy2045/angular-selectize) into my project. This will create a search box that allows for entering multiple values to filter all cells in an ng-Table without the need to ...

Pager.js utilizing Deferred Bindings

I am currently working on using Pager.js to develop a single page application. The structure I have set up is as follows: #word/definition #word/example #word/synonym This means that definition, example, and other elements are divs with page bindings: & ...

Warning in Closure compiler: [JSC_POSSIBLE_INEXISTENT_PROPERTY] The property TextEncoder may not be defined on this object

In my Node.js application, when using the TextEncoder class, I typically do the following: const TextEncoder = require("util").TextEncoder; Although the code functions correctly, I am receiving an undesired warning from the Closure compiler: [JS ...

Encountered an issue with Nextjs dynamic routes and static pages where the error message states that the `paths` variable needs to be an

I have been following the official Next.js guide on generating statically generated pages with dynamic routes (Nextjs - Dynamic Routes). However, I am facing an issue when trying to generate pages with fetched data. The error message I am receiving is as f ...

Organizing an Ordered List of Items into Alternating Columns Using HTML

I am in the process of developing a responsive HTML design to showcase an array of organized data. For smaller screens, the layout will consist of a single column displaying items sequentially. However, on larger screens, the design should adapt to featur ...

Pointer Dereference in C Programming Language

Recently delving into the world of C programming, I've encountered a challenge while attempting to execute a set of code in conjunction with user input. Struggling to resolve an issue that appears at this particular line: char names[SIZE][LENGTH]; ...

Exploring the method to retrieve key value pairs within an array object using JavaScript

I have an array of JSON objects and I am trying to extract it as key-value pairs. Here is the code snippet: var fs = require('fs'); var parameters = { 'Tenantid': 'a62b57-a249-4778-9732', "packagecategoryn ...

Learning to transform EST time data into local time within JavaScript utilizing moment.js and Date objects

The recorded date and time is "03/19/2020 13:15:00" in Eastern Standard Time (EST). When attempting to convert it to the local timezone, I have tried various methods, such as using moment.js to change the format from 'MM/DD/YYYY HH:mm:ss' to UT ...

Can one intercept the window.location.replace event?

Suppose I am currently browsing the URL "example.com/somepage#somehash" and then decide to execute window.location.hash = "anotherhash", the URL will be updated to "example.com/somepage#anotherhash". This action triggers the window.hashashchange event. On ...

Tips on toggling between slides with Bootstrap Carousel

I am in the process of designing a portfolio website and have encountered a challenge. I want to divide it into two sections - a brief introduction and a carousel for showcasing projects. While I have managed to set up both sections, I'm facing an iss ...

How can I create a hover effect for a span element using html and css?

I have encountered an issue with hover color in span classes. I managed to successfully create two classes on this page, but the hover effect is not working on other classes. To troubleshoot, I included a link to my test page below. Can you please review i ...

How can you efficiently remove empty lines from the start and end of an array?

Check out this script: <?php $lines[] = ''; $lines[] = 'first line '; $lines[] = 'second line '; $lines[] = ''; $lines[] = 'fourth line'; $lines[] = ''; $lines[] = ''; $lineCount ...

Enhancing User Experience with Load Indicator during State Changes in React Native

I'm facing an issue where the page for displaying a single item is loading slowly - I need to delay the page from loading until the object has changed. After checking the navigation params through console log, I can see that the id changes when each b ...

Access JSON value using jQuery by key

Creating a JSON structure that contains information about attendees: { "attendees": [ { "datum": "Tue, 11 Apr 2017 00:00:00 GMT", "name": " Muylaert-Geleir", "prename": "Alexander" }, { "datum": "Wed, 12 Apr 2017 ...

Disabling JavaScript for a particular page using Selenium:

My current challenge involves navigating to a webpage, locating a link to another page within it, and proceeding to that link without using javascript. One approach I've considered involves the following method: options = Options() options.add_exper ...

Why is npm attempting to compile a previous version of my code?

Being a complete newbie to npm and node.js, I hope you can bear with me if I'm lacking in providing the right details. I am working on developing a plugin for a website that utilizes an out-of-the-box framework within npm. Initially, everything was ru ...

Tips for operating an Express application with React in production mode

My web application has a specific file structure as shown in the image below. https://i.stack.imgur.com/Etzdb.png I'm facing difficulties running my web app with the React Production Build. The following code snippet in my index.js doesn't seem ...

Utilizing Javascript to share images from a public Facebook page to a user's timeline via the Facebook API

Can someone assist me with finding a way to share a photo from a public Facebook page to the user's timeline using JavaScript? Is it possible to achieve this with FB.api or FB.ui? I have successfully shared feeds to the timeline using FB.ui, but am no ...

Having trouble getting two different filters to work properly when filtering data in AngularJs

I have created a plunkr to demonstrate my current situation: The user is required to type a word into the textbox, and upon clicking the button, an angular service retrieves data from a DB based on the input text. The retrieved data is then displayed in a ...