I am encountering an issue with my function where I aim to prevent the creation of a node using duplicate coordinates

Trying to avoid creating a node with existing coordinates, I implemented a check in my code. The check is supposed to determine if there are any nodes with the same coordinates already present. However, it seems that the check is not working as expected and I'm unable to locate the mistake.

The NodeX and NodeY ids correspond to input type number elements.

function create_node(){
    var coordinates = [parseFloat(document.getElementById('NodeX').value), parseFloat(document.getElementById('NodeY').value)];
    var coordinate_check = 0;
    for (var item of node_coordinates){
        if (item == coordinates){
            coordinate_check = 1
        }       
    }
    if (document.getElementById('NodeX').value == ""){
        console.log('Please enter X coordinates.')
    }
    else if (document.getElementById('NodeY').value == ""){
        console.log('Please enter Y coordinates.')
    }
    else if (coordinate_check == 0){
        if (nodes.length == 0){
            nodes.push(1);
        }
        else{
            nodes.push(1+nodes[nodes.length-1]);
        }
        node_coordinates[nodes.length-1] = coordinates;
        node_loads[nodes.length-1] = [0, 0, 0];  
        restraints_names[nodes.length-1] = 'none';
        restraints_dofs[nodes.length-1] = ['free','free','free'];
        document.getElementById('nodeselect').innerHTML = update_nodelist();
    }
    else{
        console.log('Node Exists!');
    }
    console.log(nodes);
    console.log(node_coordinates);
};

Answer №1

After swapping out the

(item == coordinates) section

for

(parseFloat(document.getElementById('NodeX').value) == item[0] & parseFloat(document.getElementById('NodeY').value) == item[1])

The code now functions as intended. What are the distinctions between these two comparisons?

Answer №2

When comparing item such as 0 with the array coordinates containing two values like [2, 1], it will never evaluate to true because 0 != [2, 1].

for (var data of node_coordinates){
    if (data == coordinates){
        coordinate_check = 1
    }       
}

If you need to compare two one-dimensional arrays, you can use this function:

const compareArrays = (arr1, arr2) => arr1.length === arr2.length && arr1.every((element, index) => element === arr2[index]);

Additionally, refer to How to compare arrays in JavaScript?

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

Invoke a Python function from JavaScript

As I ask this question, I acknowledge that it may have been asked many times before. If I missed the answers due to my ignorance, I apologize. I have a hosting plan that restricts me from installing Django, which provided a convenient way to set up a REST ...

Distributing JWT to the recipient using Express

Allow me to provide you with an overview of my application, which is quite straightforward. The main concept revolves around a user inputting their accountname and password into an html form on the /Login page like so: <form action="/Login" m ...

Storing the Token from the AJAX Login API Call in JavaScript: Best Practices for Keeping Credentials Secure

After sending my credentials to a login API, I received a successful response containing user data and a token. I would like to know how I can store this information so that the user doesn't have to log in every time. Is it possible for me to save the ...

Vue-Router functions only on specific routes

While my vue-router correctly routes the URL for all menu buttons, it's not displaying each Vue component properly. You can see a demonstration here. Here is a snippet of my HTML (using Vuefy) <div class="navbar-start"> <a ...

Guide on sending a request to an API and displaying the retrieved information within the same Express application

I recently developed a basic express app with API and JWT authentication. I am now attempting to enhance the app by incorporating page rendering through my existing /api/.. routes. However, I am facing challenges in this process. app.use('/', en ...

reloading a webpage while keeping the current tab's URL selected

I want to incorporate a feature I saw on the jQuery website at http://jqueryui.com/support/. When a specific tab is pressed, its contents should open. However, when the page is refreshed, the same tab should remain open. I'm trying to implement this i ...

Tips on downloading an image using the URL in nestjs

I'm trying to retrieve a link and save the associated image in the static folder, but I seem to be encountering some issues with my code. Here's what I have so far: @Injectable() export class FilesService { createFileFromUrl(url: string) { t ...

A JavaScript async function with a nested call inside

Below is my node function for the API server: router.post('/find', async (req, res) => { try { const firewalls = []; let count = 0; const devices = await Device.find({ ...req.body }); devices.forEach(async (item) => { ...

Prevent users from navigating back after logging in on a Reactjs application

Is there a way to prevent users from using the browser's back button after redirecting them to another application in ReactJS? In my scenario, I have two applications running simultaneously. Upon successful login, I check the user type. If the conditi ...

Arrow function returns itself, not the function

While working with React, I've been using utility functions for managing API calls. I noticed that when the arrow function is no longer anonymous, it successfully returns a pending promise – which is exactly what I want. However, if the arrow functi ...

Investigating TLS client connections with node.js for troubleshooting purposes

I am currently facing an issue while setting up a client connection to a server using node.js and TLS. My query revolves around how I can gather more information regarding the reason behind the connection failure. It would be great if there is a way to ob ...

Prevent the browser from autofilling password information in a React Material UI textfield when it is in focus

I am currently utilizing React Material UI 4 and I am looking to disable the browser autofill/auto complete suggestion when focusing on my password field generated from `TextField`. Although it works for username and email, I am encountering issues with d ...

Error during minification process for file opentok.js at line 1310: react-scripts build

I encountered an error while trying to minify the code in my React project using npm run build. The snippet below seems to be the cause of the issue. Any suggestions on how I can resolve this problem? const createLogger = memoize(namespace => { /** ...

How can I retrieve the updated input value once a specific key has been pressed in the prototype?

After a customer presses any key, I would like to check an email. Below is the code I am using: document.observe("dom:loaded", function() { $('billing:email').observe('keypress', function(event){ console.log(event.element(). ...

"VueJS application can now be restarted with the simple push of a

Is there a way to reload the application in VueJS when a button is pressed? I've attempted the following: this.$nextTick(() => { var self = this; self.$forceUpdate(); }); However, $forceUpdate() does not serve the purpose I need. ...

Fetching Dependencies with NPM from the package.json file

I am feeling a bit puzzled. While working on my laptop, dependencies were automatically added to my package.json file as I installed them for my project. This is how it appears: "main": "webpack.config.js", "dependencies": { "immutable": "^3.7.6", ...

Click event triggers nested bootstrap collapse

As a beginner in bootstraps and coding, I am currently experimenting with opening the main bootstrap panel using an onclick event that includes nested sub panels. Here is my index.html file containing the panels and the button; <link href="https://m ...

Angular HTTP client implementation with retry logic using alternative access token

Dealing with access tokens and refresh tokens for multiple APIs can be tricky. The challenge arises when an access token expires and needs to be updated without disrupting the functionality of the application. The current solution involves manually updati ...

Navigating between divs with a 100% height using up and down movements

I am working on a website that is structured into different sections using divs with shared classes but unique IDs. Each div is set to take up 100% of the viewport height. To navigate between these sections, I want to provide Up/Down arrow buttons for user ...

What is the best way to stop this Jquery slider from moving?

I've been struggling with this issue for what feels like forever, and it's driving me crazy! I have a slider on the homepage that I'm trying to enhance with a "click to pause" feature (and maybe even a click to resume, for good measure). I ...