What is causing the undefined result when duplicate elements are encountered?

 const cardChild = document.querySelectorAll('.card i');
 const cardsArray = ['a','a','b','b','c','c']; 
 const matchArray = [];

function cardsToClass() {
     for (i = 0; i < cardChild.length; i++) {

         let newCard = cardsArray.pop();
         let newCardClass = cardChild[i];
         matchArray.push(cardsArray[i]);

         newCardClass.className += newCard;
         console.log(cardsArray);
     }; }

Hello friends! The code above showcases a function that utilizes .pop() to assign elements from 'cardsArray' as classes in a DOM element. The goal is to have two arrays ('cardsArray' and 'matchArray') with identical contents. We are almost there, but when I check 'matchArray', it seems off:

 ['a','b','c',undefined,undefined,undefined]

I suspect the issue might be at:

 matchArray.push(cardsArray[i]);

However, I'm not entirely sure. Any insights into why it's not capturing the duplicate elements?

Thank you!

Answer №1

Instead of copying the array from the first position to the last and removing the last item with pop(), try using unshift() which will resolve the issue of half of the array endings up as undefined.

If you're unsure about the purpose of the code, including the HTML might provide some insight.

Here is the revised code:

//const cardChild = document.querySelectorAll('.card i');
 const cardsArray = ['a','a','b','b','c','c']; 
 const matchArray = [];

function cardsToClass() {
     for (i = 0; i < cardsArray.length; i++) {

         let newCard = cardsArray.unshift();
         //let newCardClass = cardChild[i];
         matchArray.push(cardsArray[i]);

         //newCardClass.className += newCard;

     };
console.log(cardsArray);
console.log(matchArray);
}
     
cardsToClass() 

Answer №2

The reason behind this issue is that when you use the .pop method, it alters the original array itself.

Check out the official documentation


As .pop changes the contents of cardsArray, the size of the array decreases with each iteration of the loop.

During every loop iteration, cardsArray appears as:

  1. cardsArray = ['a','b','c','a','b','c'];
  2. cardsArray = ['a','b','c','a','b'];
  3. cardsArray = ['a','b','c','a'];
  4. cardsArray = ['a','b','c'];
  5. cardsArray = ['a','b'];
  6. cardsArray = ['a'];

Therefore, starting from the third iteration (i = 2), the value of cardsArray[i] becomes undefined

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

Ensuring validation on an input field following the addition of a new field sharing the same class

Whenever the "Add" button is clicked, an input field with the same class name should be created. However, a validation check needs to be performed before creating the input field. The issue is that the validation is only working the first time and not duri ...

C syntax: reference to an array of characters (string)

What is the reason behind writing pointers to arrays of chars (i.e. strings) in the following format: char *path Instead of: char *path[] or a different method? Is there a way to create a pointer to a single char rather than a string? ...

Method for developing a screen-sharing application

I'm in the process of developing a screen sharing application. I initially attempted to utilize WebRTC, but encountered numerous challenges with it. As a result, I am contemplating an alternative approach outlined below. For the Host side, capture ...

Retrieving items from an array by matching them with items in another array

Exploring the world of coding, I recently embarked on creating minesweeper using windows forms. An array structure is at my disposal: tiles = new PictureBox[30,16]; Additionally, there's another array defined like so: mines = new int[30,16]; The m ...

Problem Encountered with array_key Encoding Using UTF-8

There have been numerous discussions on UTF-8 encoding issues, with most focusing on encoding array values. My concern lies specifically with the array keys. I am seeking a solution to encode an array that contains keys with special characters. Here is ...

Having difficulty displaying a partial view within a view while making an AJAX call

Trying to figure out what's missing in my code. I have a view with some radio buttons and I want to display a different partial view when a radio button is selected. Here's the snippet of my code: Controller public ActionResult Method(string va ...

effortlessly eliminate the Google MyMap watermark from an iframe using ReactJS

I am new to ReactJS and I would like help on how to hide the watermark on a Google My Map. Can someone please assist me with this? <iframe src="https://www.google.com/maps/d/u/1/embed?mid=1OMSkPKZi-U-CnmBr71zByNxp8HYi-vOc&ehbc=2E312F" fram ...

A guide on calculating the total values for each key in a multidimensional array

If we take an array with the following structure: $data = array( 'blue' => array( '1' => array(4), '2' => array(8, 3) ), 'yellow' => array( '2' => array(3 ...

Leveraging an array in a function parameter

I'm currently developing a program to calculate values from two arrays. I'm facing challenges related to passing and utilizing arrays in my functions. Below is the code snippet that I am working on: #include <stdio.h> #include <string.h ...

What causes a JSON error upon deleting a list in Replit?

Need assistance with deleting a specific index from a list stored in a json file The json file structure { "0": [ "0", "1", "2", "3" ] } The Python program import json with o ...

When an input element is being controlled from outside the modal using a portal, it is losing focus after a key press

[Resolved] The input component is experiencing a focus issue when any key is pressed, only when its value is controlled from outside of the portal. NOTE: I apologize for any confusion. While writing this post, I identified the problem in my code, but dec ...

What is the best way to incorporate multiple pages into a Node JS and Express application?

After completing a tutorial on Node JS for RPI (https://www.youtube.com/watch?v=QdHvS0D1zAI), I encountered an issue when trying to add multiple websites to my web app. While everything works fine locally on localhost:5000/page2, once I make the app public ...

Ways to prevent a high-powered Javascript loop from causing the browser to freeze

I am currently utilizing Javascript to parse an XML document containing roughly 3,500 elements. I have implemented a jQuery "each" function for this purpose, although I remain open to considering alternative looping methods. One issue that has surfaced ...

Using jquery to insert a new row into a table

Here is the HTML and Javascript code I have been working on. My goal is to clone a row in a table and update the ids of each input element. While debugging the script, I can see the row being cloned and added to the table temporarily, but it disappears f ...

During the program's runtime, p5.js unexpectedly encounters a problem reading my update function at a random point

I'm currently working on a project where I want to create a program that removes particles from an array when they reach the right end of the canvas. let P = []; let n = 10; function setup() { createCanvas(500,500); for(let i = 0; i < ...

In React, what is the correct term for "selection boxes" when choosing multiple items in Finder?

I'm in search of a React component that allows me to select multiple elements on the screen by clicking, holding, and forming a square around them. I've tried searching for terms like 'selection box' and 'React select elements,&apo ...

Is it possible to continuously divide or multiply numbers by 2 without encountering any rounding errors when working with floating point numbers?

binary can only represent those numbers as a finite fraction where the denominator is a power of 2 Are calculations done in binary/floating point format still accurate, even after multiple additions or multiplications by 2 without any rounding errors? co ...

What is the correct method for successfully navigating arrays with pointers?

Currently, I am working on implementing Djikstra's algorithm to find the shortest path through a maze. However, when I input my array, I encounter a warning stating: warning "passing argument 1 of 'traverse' from incompatible pointer type ...

Ways to conceal a div element when the JSON data does not contain a value

If the value in "desc" is empty, then hide <div24> and <popup-desc>. html <div class="popup"> <div class="popup-top" style="background-color: '+e.features[0].properties.fill+';"> ...

Unraveling the mystery: How does JavaScript interpret the colon?

I have a quick question: When I type abc:xyz:123 in my GoogleChrome browser console, it evaluates to 123. How does JavaScript interpret the : symbol in this scenario? ...