I am working on a LeetCode problem, I want to assign a variable to a sorted copy of an array.
sortedHeights = heights.toSorted()
However, this returns the following error heights.toSorted is not a function
.
I looked up the issue on MDN, and found the following code snippet:
const months = ["Mar", "Jan", "Feb", "Dec"];
const sortedMonths = months.toSorted();
console.log(sortedMonths); // ['Dec', 'Feb', 'Jan', 'Mar']
console.log(months); // ['Mar', 'Jan', 'Feb', 'Dec']
I try to run this code snippet as well on WebStorm and I get the same error, however, when I run it in a browser it works. Why is that?
At the time of this answer, Array.prototype.toSorted()
is supported by Node.js version 20+. Most developers use the Node.js LTS version (currently version 18). So if you're using Node.js version 19, 18 or lower in WebStorm, .toSorted()
is not supported.
For the case of LeetCode, I see that it currently uses Node.js 16 to run your code. So you might want to resort to this alternative (and effectively equivalent) code for the time being:
sortedHeights = [...heights].sort()
Also note that .toSorted()
is currently supported in recent versions Chrome and Edge (from version 110), Safari (from version 16), Firefox (from version 115) and some other browsers, it's not supported in older versions - just in case you made an assumption that it works in all browsers.
Check the Array.prototype.toSorted() MDN browser compatibility section for latest support details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With