JSFiddle - React, Tailwind, and code Playground

by vjeux

JavaScript

Array.prototype.last = function () { return this[this.length - 1]; };

var ends = Object.create(null);

function pack(list) {
    list = list.map(function (group) { return group.concat(); });
    
    list.forEach(function (group) {
        ends[group.last()] = group;
    });

    list.forEach(function (group) {
        if (group[0] && ends[group[0]]) {
            Array.prototype.push.apply(ends[group[0]], group);
            group.splice(0, group.length);
            ends[group.last()] = group;
        }
    });

    return list.filter(function (group) {
        return group.length > 0;
    });
}

console.log(pack([['a', 'b'], ['b', 'c'], ['z', 'a']]));