[Solved] Sorting by the elements that come first in the array


You could use sorting with map by using a temporary object with a hashtable for the same group counter.

The sorting happens with the group.

The result is mapped with index of the sorted temporary array.

var array = ['H', 'A', 'H', 'A'],
    groups = Object.create(null),
    counter = 0,
    result = array
        .map((v, index) => ({ index, group: groups[v] = groups[v] || ++counter }))
        .sort((a, b) => a.group - b.group)
        .map(o => array[o.index]);

console.log(result);

The same, but with a Map for the order of the first occurence.

var array = ['H', 'A', 'H', 'A'],
    map = new Map;

array.forEach(v => map.has(v) || map.set(v, map.size + 1));

array.sort((a, b) => map.get(a) - map.get(b));

console.log(array);

solved Sorting by the elements that come first in the array