Javascript 2d array indexOf

前端 未结 9 1620
既然无缘
既然无缘 2020-11-28 12:03

I have a 2d array like this:

var arr = [[2,3],[5,8],[1,1],[0,9],[5,7]];

Each index stores an inner array containing the coordinates of some

9条回答
  •  没有蜡笔的小新
    2020-11-28 12:19

    Here is a solution done using prototype so the usage resembles that of indexOf but for 2d arrays. Use in the same way: arr.indexOf2d([2,3]);

    var arr = [[2,3],[5,8],[1,1],[0,9],[5,7]];
    
    Array.prototype.indexOf2d = function(item) {
        // arrCoords is an array with previous coordinates converted to strings in format "x|y"
        arrCoords = JSON.stringify(this.map(function(a){return a[0] + "|" + a[1]}));
    
        // now use indexOf to find item converted to a string in format "x|y"
        return arrCoords.indexOf(item[0] + "|" + item[1]) !== -1;
    }
    
    arr.indexOf2d([2,3]); // true
    arr.indexOf2d([1,1]); // true
    arr.indexOf2d([6,1]); // false
    

提交回复
热议问题