while I was cracking the leet code task I bumped into some unexpected behavior of the .sort function, so I couldn’t finish my task until I implemented the insertion sorting function myself which helped me to sort an array of chars properly.
So the question:
why this function doesn’t compare with all the array members?
function customSortString(order: string, s: string): string {
const map={};
for(let i=0;i<order.length;i++){
map[order[i]]=i;
}
const newStr=[...s].sort((a,b)=>{
if(map[a]===undefined || map[b]===undefined || a===b){
return 0;
}
if(map[a]<map[b]){
return -1;
}
return 1;
})
return newStr.join('');
};
if I call
customSortString("exv","xwvee")
it will return ‘xweev’, but expected "eexvw"
here is a description of the problem

If I put console.log into to sorting function
w x
v w
e v
e w
e v
e e
e v
So I can see, that "x" is not compared with "e". But if it did compare it would return 1 and would display "e" first then "x"
I hope I explained clearly, but ask questions if you didn’t
>Solution :
You need to move unknown characters to the end, with a large value.
function customSortString(order, s) {
const map = {};
for (let i = 0; i < order.length; i++) map[order[i]] = i + 1;
return [...s]
.sort((a, b) => (map[a] || Infinity) - (map[b] || Infinity))
.join('');
};
console.log(customSortString("exv", "xwvee"));