Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript prototype sorting function don't compare with all members

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

customSortString("exv","xwvee")

it will return ‘xweev’, but expected "eexvw"

here is a description of the problem
enter image description here

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"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading