0

I don't want to create a node with existing coordinates. So that I created a check. It is checking if there is another same coordinate. If there is same coordinate, coordinate_check variable becomes 1. However, the check is not working. I could not find where is my mistake.

NodeX and NodeY ids are belonging input type number.

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];  //[Forcex, Forcey, Moment]
        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);
};```
Mr. Toç
  • 21
  • 5

2 Answers2

0

When I change

(item == coordinates) part

with

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

the code runs as I desired. What is the differences between two comparison?

Mr. Toç
  • 21
  • 5
0

You are comparing item e.g. 0 with array coordinates with two values inside e.g. [2, 1] I'll never be true because 0 != [2, 1].

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

If you want to compare two single dimensional arrays you may try:

const compareArr = (a, b) => a.length === b.length && a.every((ele, index) => ele === b[index]);

Also you should check How to compare arrays in JavaScript?

RauboLuk
  • 421
  • 1
  • 3
  • 7