JSFiddle - React, Tailwind, and code Playground

JavaScript

var matrixes = [
  [
    [3, 2, 1],
    [1, 2, 3],
    [3, 1, 3]
  ], // Должен выводится 3
  [
    [3, 2, 1],
    [1, 2, 3],
    [3, 2, 1]
  ], // Должен выводится 0
  [
    [1, 0, 0, 0],
    [0, 1, 0, 0],
    [0, 0, 1, 0],
    [0, 0, 0, 1]
  ], // Должен выводится 4
  [
    [2, 4],
    [4, 2]
  ] // Должен выводится 0 
];

matrixes.forEach(matrix => {
  console.log("------------------------");
  console.table(matrix);
  console.log(calc(matrix));
});

function calc(matrix) {
  let template = matrix[0];
  let result = matrix.reduce((acc1, items, index1) => {
    if (index1 === 0) return acc1;
    template = template.reverse();
    acc1 += items.reduce((acc2, item, index2) => {
      acc2 += Math.abs(template[index2] - item);
      return acc2;
    }, 0);
    return acc1;
  }, 0);
  return result;
}