I've seen a post explaining how to do this but in python, but it was done in a python library, so I tried converting it to javascript without a library and this is how it turned out.
function board_to_fen(board)
{
let result = "";
for(let y = 0; y < board.length; y++)
{
let empty = 0;
for(let x = 0; x < y.length; x++)
{
let c = y[x][0];
if(c == 'w' || c == 'b') {
if(empty > 0)
{
result += empty.toString();
empty = 0;
}
if(c == 'w')
{
result += y[x][1].toUpperCase();
} else {
result += y[x][1].toLowerCase();
}
} else {
empty += 1;
}
}
if(empty == 0)
{
result += empty.toString();
}
result += '/';
}
result += ' w KQkq - 0 1';
return result;
}
let board = [
['bk', 'em', 'em', 'em', 'em', 'em', 'em', 'em'],
['em', 'bn', 'em', 'wr', 'em', 'wp', 'em', 'em'],
['br', 'em', 'bp', 'em', 'em', 'bn', 'wn', 'em'],
['em', 'em', 'bp', 'bp', 'bp', 'em', 'wp', 'bp'],
['bp', 'bp', 'em', 'bp', 'wn', 'em', 'wp', 'em'],
['em', 'em', 'em', 'em', 'em', 'em', 'em', 'em'],
['em', 'em', 'em', 'wk', 'em', 'em', 'em', 'em'],
['em', 'em', 'em', 'em', 'em', 'em', 'em', 'em'],
];
console.log(board_to_fen(board));
The correct fen for that Chess Board Diagram is "k7/1n1R1P2/r1p2nN1/2ppp1Pp/pp1pN1P1/8/3K4/8 w KQkq - 0" but in the console it prints out "0/0/0/0/0/0/0/0/ w KQkq - 0 1".