Writing a function to validate if an array is a valid sudoku board

Kevin Xie
1 min readJan 26, 2021
function isValidSudoku(board) {
let store = {
rows: {},
cols: {},
square: {},
};
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
const box = board[i][j];

if (!store["rows"][i] && box !== ".") {
store["rows"][i] = [];
store["rows"][i].push(box);
} else if (box !== "." && !store["rows"][i].includes(box)) {
store["rows"][i].push(box);
} else if (store["rows"][i] && store["rows"][i].includes(box)) {
return false;
}

if (!store["cols"][j] && box !== ".") {
store["cols"][j] = [];
store["cols"][j].push(box);
} else if (box !== "." && !store["cols"][j].includes(box)) {
store["cols"][j].push(box);
} else if (store["cols"][j] && store["cols"][j].includes(box)) {
return false;
}

const squareRowId = Math.ceil((i + 1) / 3);
const squareColId = Math.ceil((j + 1) / 3);
const squareId = `${squareRowId}-${squareColId}`;

if (!store["square"][squareId] && box !== ".") {
store["square"][squareId] = [];
store["square"][squareId].push(box);
} else if (box !== "." && !store["square"][squareId].includes(box)) {
store["square"][squareId].push(box);
} else if (
store["square"][squareId] &&
store["square"][squareId].includes(box)
) {
return false;
}
}
}
return true;
}

--

--