1

i have an array, filled with arrays containing multiple objects. I have a function that returns if an object exists in there or not, but sometimes it cant find an object that is definitely in there. I put a ton of console logs so i can keep track of everything and show you the console. Here is the code:

var adjacent = inChain(x, y - 1, array);
array[adjacent].push({x: x, y: y})

So here i call the inChain function which searches for the object and then returns the index its in. The error is on the 2nd line at push as if it cant find it, adjacent will be null.

Function:

function inChain(x, y, array)
{
    var currentPiece = {x: x, y: y};
    
    console.log("checking array below");
    console.log(array);
    console.log("checking if this object exists");
    console.log(currentPiece);
    
    for(let i = blackChains.length; i--;)
    {
        for(let j = blackChains[i].length; j--;)
        {
            if (JSON.stringify(blackChains[i][j]) === JSON.stringify(currentPiece))
            {
                console.log("it does at " + i);
                return i;
            }
        }
    }    
    console.log("doesnt exist");
    return null;
}

So as you can see by the console logs, it will say each step, first it will show the array its looking in, then the object its looking for. heres a screenshot of it in action:

enter image description here

So you can see the array contains 1 array which contains 1 object. An object with the properties x: 3, y: 2

Then you can see the object its searching for, an object with the exact same properties

Would anyone know why its sometimes not finding it? and sometimes it does?

12
  • What are the values of x, y, and array? Commented Jun 1, 2017 at 9:44
  • I think the comparison using JSON.stringify() is not stable enough. Consider creating some hash-function and compare by the hash values of your objects. Commented Jun 1, 2017 at 9:44
  • in this case x would be 3, y would be 3 and the array would be the array that contains all the objects in this case. it would search for x, y-1 in that array so it becomes 3,2, array Commented Jun 1, 2017 at 9:46
  • Do you think its because of the JSON.stringify? i thought that too but im not sure Commented Jun 1, 2017 at 9:46
  • a= {}; a.x = 1; a.y=2; b={}; b.y=2; b.x=1; leads to JSON.stringify(a) != JSON.stringify(b) although a comparison for each individual property says otherwise. Commented Jun 1, 2017 at 9:48

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.