Diagonalize nd-arrays in javascript