# Issue

This Content is from Stack Overflow. Question asked by Joji

I am writing a function that takes a 2d array that represents a grid for a tic tac toe game. Initially it is `[[0, 0, 0], [0, 0, 0], [0, 0, 0]]` and there is player 1 which is represented as `1` and player 2 as `-1`.

The function to check the winner should return the winner if there is actually a winner.

My attempt is this:

``````  const checkIfWin = (b) => {
if (b == b && b == b) return b
if (b == b && b == b) return b
if (b == b && b == b) return b
if (b == b && b == b) return b
if (b == b && b == b) return b
if (b == b && b == b) return b
if (b == b && b == b) return b
if (b == b && b == b) return b
}

checkIfWin([ [ 1, 0, 0 ], [ 0, 1, 0 ], [ -1, -1, 1 ] ]) // 1

``````

It works but I don’t think it is really elegant or clean and I wonder if there is a better way to check a winner and return the winner?

# Solution

1. Use two helper functions: `checkRow(i)` and `checkColumn(i)`, which check if all values are same in a given row and column respectively.
2. For `i` in range `[0, number of rows]`, use `checkRow(i)`
3. For `i` in range `[0, number of columns]`, use `checkColumn(i)`
4. If still no winner is found, check the diagonals (for which you can use another helper function)

This is extremely simple to program, so I’ll leave that up to you. But you can use this approach to break down the problem into simpler pieces.

``` This Question was asked in  StackOverflow by  Joji and Answered by Abhinav Mathur It is licensed under the terms of
CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.```