DEV Community

Discussion on: Finding the coordinates of an element in a 2D array

Collapse
 
paratron profile image
Christian Engel • Edited

If you go for speed, working without callback functions should be faster!

function findCoordinate(in2dArray, searchValue){
    for(let x = 0; x < in2dArray[0].length; x++){
        for(let y = 0; y < in2dArray.length; y++){
            if(in2dArray[y][x] === searchValue){
                return {x, y};
            }
        }
    }
    return null;
}
Enter fullscreen mode Exit fullscreen mode

Maybe you can throw this against your benchmark 😅

A note:
When working with computers and coordinates I never had the case that the horizontal position was labeled with y.

So in my code, I chose to use x for the horizontal axis.

Another difference to your function is that it returns null if no coordinate was found.

Collapse
 
paratron profile image
Christian Engel

Here is another approach when you want to go for SPEED (maybe you need to look up coordinates very often?).

let fastMap = null;

function computeFastMap(in2DArray){
    fastMap = {};

    for(let x = 0; x < in2dArray[0].length; x++){
        for(let y = 0; y < in2dArray.length; y++){
            fastMap[in2dArray[y][x]] = {x, y};
        }
    }
}

function find2DCoordinate(value){
    if(!fastMap){
        throw new Error("Compute the fastMap, first!");
    }

    return fastMap[value] || null;
}
Enter fullscreen mode Exit fullscreen mode

To make this work, you need to call computeFastMap(grid) at the beginning, once.
Afterwards, you can call find2DCoordinate() often but since all coordinates are pre-computed, the lookup in the
map is basically "for free" and will be VERY fast.

Collapse
 
kbravh profile image
Karey Higuera

Good call, I hadn't worked under the assumption of needing to do multiple lookups. It reminds me of a tweet I saw of using coordinate pairs in tuples for dictionary lookups in Python twitter.com/nedbat/status/15225434...