DEV Community

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

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...