Search code examples
javascriptarrayssearchcreatejstween

Searching a multi-dimensional array of coordinates for an exact match in javascript


I have an array of coordinate points that I am using to run animations and would like to get the current position of an image and determine what index of the array that position is.

var pointArray = [{x:70, y:500},
    {x:120, y:500},
    {x:150, y:500},
    {x:178, y:488},
    {x:193, y:465},
    {x:205, y:440},
    {x:228, y:418},
    {x:255, y:408},
    {x:286, y:405},
    {x:317, y:410},
    {x:345, y:422},
    {x:372, y:438}];

pointArray[indexOf(player1.x)] OR pointArray[indexOf("{x:70, y:500}")] both return -1, the default value for when a search term is not found. What is the proper syntax for searching a multidimensional array?

Note: the point array above is an abridged version, but in the full version coordinates do have duplicated x or y values, so I need to do more than just search for 1 of the 2 coordinate values.


Solution

  • You would have to do a custom search because your new object (the argument to indexOf()) is different to the ones in the array (unless of course you had a reference to the one you're trying to search for).

    An easy way to do it would be...

    var match = {x:70, y:500};
    for (var i = 0; i < pointArray.length; i++) {
         if (match.x == pointArray[i].x && match.y == pointArray[i].y) {
             break;
         }
    }
    

    Now, i will be the index of where the result was found. You'd need to handle the case where it wasn't found.