is array.sort() implementation incosistent?
I would like to give some feedback about ...
From: https://js.checkio.org/mission/most-wanted-letter/solve/
HTTP_USER_AGENT:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36
My code:
function mostWanted(data) { return (!data) ? '' : data.toLowerCase().replace(/[^\w]/g, '') .split('').sort().join('') .match(/(.)\1*/g).sort((a, b) => b.length - a.length)//[0][0] Uncomment this to get the most wanted letter }
The issue :
The code should preserve the order after the second sort, it does that untill it reaches 11 unique characters.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
"If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behavior, thus, not all browsers"
I understand that, but it's odd that changes after a set ammount of unique characters.
I would know: Is this intended?
// First time I encounter the issue >>>mostWanted("Lorem ipsum dolor sit amet") <<<["ooo","mmm","ee","ii","ll","rr","ss","tt","a","d","p","u"] // Expected result // ["mmm", "ooo", "ee", "ii", "ll", "rr", "ss", "tt", "a", "d", "p", "u"]
I checked this in the chrome browser and it works.
console.log("Lorem ipsum dolor sit amet".toLowerCase().replace(/[^\w]/g, '') .split('').sort().join('') .match(/(.)\1*/g).sort((a, b) => b.length - a.length)) (12) ["mmm", "ooo", "ee", "ii", "ll", "rr", "ss", "tt", "a", "d", "p", "u"]
Examples:
// This works fine... >>>mostWanted("OOOMMM") <<<["mmm","ooo"] // This works fine... >>>mostWanted("aOOObMMMc") <<<["mmm","ooo","a","b","c"] // This works fine... >>>mostWanted("abOOOcdMMMef") <<<["mmm","ooo","a","b","c","d","e","f"] // this doesn't work anymore, >>>mostWanted("abcOOOefgMMMhil") <<<["ooo","mmm","c","e","f","b","h","i","l","a","g"] // I think after 10 unique character changes the sorting method. This doens't work >>>mostWanted("abcdefghiOOOMMM") <<<["ooo","mmm","c","d","e","b","g","h","i","a","f"] // With 10 works >>>mostWanted("abcdefghOOOMMM") <<<["mmm","ooo","a","b","c","d","e","f","g","h"] // With 10 unique character but 11 character works just fine >>>mostWanted("AAbcdefghOOOMMM") <<<["mmm","ooo","aa","b","c","d","e","f","g","h"]