Sort 2D array by matching the last values with the first one in the next index

Solution 1:

For the example you gave the easiest solution would be to sort the 2d array by the second element of each inner array, as follow:

let array = [[1,0],[2,1],[0,3],[3,2]];
array.sort((a, b) => b[1] - a[1]);

In that way you can sort the array with the sort method according to the elements in the inner arrays.

let array = [[1,0],[2,1],[0,3],[3,2]];
array.sort((a, b) => b[1] - a[1]);
console.log(array);

Solution 2:

You could take an object as reference and rebuild the array by taking the chained items.

const
    getItems = (reference, value) => {
        const a = reference[value];
        return a ? [a, ...(a[1] === 0 ? [] : getItems(reference, a[1]))] : [];
    },
    array = [[1, 0], [2, 1], [0, 3], [3, 2]],
    reference = array.reduce((r, a) => (r[a[0]] = a, r), {}),
    result = getItems(reference, 0);

console.log(result);

Solution 3:

Look at this method:

const array =  [[1,0],[2,1],[0,3],[3,2]];
const result = [...array];

// Put the subarray with the zero element first
// You can use the sort() function but I guess this method
// performs better in terms of time

for (let i = 0; i < result.length; ++i) {
  if (result[i][0] === 0) {
    result.unshift(...result.splice(i, 1));
    break;
  }
}

// Now reorder the array so that the last index of a subarray 
// matches with the first index of the other subarray

for (let i = 0; i < result.length; ++i) {
  for (let j = i + 1; j < result.length; ++j) {
    if (result[i][1] === result[j][0]) {
      // recollocate the subarray so that it matches the way we want
      result.splice(i + 1, 0, ...result.splice(j, 1));
      break;
    }
  }
}

console.log(result)