# LeetCode: Find Nearest Point That Has The Same X Or Y Coordinate Solution

`.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**2 * @param {number} x3 * @param {number} y4 * @param {number[][]} points5 * @return {number}6 */7var nearestValidPoint = function (x, y, points) {8  const calculateDist = (p1, p2) =>9    Math.abs(p1[0] - p2[0]) + Math.abs(p1[1] - p2[1])10  const validPointsWithIndex = points11    .map((point, i) => [point, i])12    .filter(([[pX, pY]]) => pX === x || pY === y)13  let min = Infinity14  let minIndex = -115  for (let i = 0; i < validPointsWithIndex.length; i++) {16    const dist = calculateDist(validPointsWithIndex[i][0], [x, y])17    if (dist < min) {18      min = dist19      minIndex = validPointsWithIndex[i][1]20    }21  }22  return minIndex23}`

leetcode

array

## Next Post

LeetCode: Design Hashmap

Mar 8, 2021

Search Posts