2
var largestNumber = function (nums) {
    let comp = (a, b) => {
        a = a.split("").reverse().join("");
        b = b.split("").reverse().join("");
        return a.localeCompare(b) > 0 ? 1 : 0;
    };
    return nums.map(v => '' + v).sort(comp).reverse().join('');

};
console.log(largestNumber([3, 30, 34, 5, 9]));

In nodejs output: 9534330
In javascript output: 9534303
What is happening?

5
  • 4
    Node is javascript... Commented Jun 29, 2020 at 23:25
  • 1
    What versions of the corresponding JS engines are you comparing? Might be some difference in the array.sort() method: twitter.com/mathias/status/1036626116654637057 Commented Jun 29, 2020 at 23:29
  • One of the engines may by default use the numeric: true option of localeCompare while the other may not... Commented Jun 29, 2020 at 23:30
  • 1
    I believe (although I'm not certain, it's a bit hard to grok) that your sort function is nondeterministic (that is, the result depends on the order in which pairs of elements are compared), in which case the result of the sort depends on however each JS engine you test it with chooses to do it. Commented Jun 29, 2020 at 23:30
  • 5
    You should be returning return a.localeCompare(b);. If you do so, you will get consistent outputs in both engines - which is 9534330. Commented Jun 29, 2020 at 23:32

1 Answer 1

2

As said in the comments your compare function is non deterministic and the 2 engines result in different outcomes. You could try the following in both versions to see consistent results 9534330.

var largestNumber = function (nums) {
    let comp = (a, b) => {
        a = a.split("").reverse().join("");
        b = b.split("").reverse().join("");
        return a.localeCompare(b);
    };
    return nums.map(v => '' + v).sort(comp).reverse().join('');

};
console.log(largestNumber([3, 30, 34, 5, 9]));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.