Сортируем существующий массив:
function sort(arr, order, key = n => n) {
const positions = new Map(order.map((n, i) => [ n, i ]));
const getPosition = n => positions.get(key(n)) ?? Number.MAX_SAFE_INTEGER;
return arr.sort((a, b) => getPosition(a) - getPosition(b));
}
Собираем отсортированный новый:
function sorted(arr, order, key = n => n) {
const ordered = new Map(order.map(n => [ n, [] ]));
const unordered = [];
arr.forEach(n => (ordered.get(key(n)) ?? unordered).push(n));
return [].concat(...ordered.values(), unordered);
}
Примеры использования:
a1 = [ '999', '290', '999', '222', '333', '987', '309', '666', '999' ];
a2 = [ '999', '222', '666' ];
sorted(a1, a2) // [ '999', '999', '999', '222', '666', '290', '333', '987', '309' ]
a1 = [ 12, 34, 6, 2, 55, 523, 23, 333, 16, 51 ];
a2 = [ 3, 5, 2 ];
sorted(a1, a2, n => +`${n}`[0]) // [ 34, 333, 55, 523, 51, 2, 23, 12, 6, 16 ]
a1 = [ 666, 'xxx', () => [], true, 1, () => null, false, 'aaa', [0] ];
a2 = [ 'boolean', 'string', 'function' ];
sort(a1, a2, n => typeof n);
a1 // [ true, false, 'xxx', 'aaa', () => [], () => null, 666, 1, [ 0 ] ]