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?
2
Answers
.toSorted()
is a new method. As you can see in the MDN doc you linked, it’s not supported in node.js yet.Firstly, it’s important to note that sorting an array involves arranging its elements in a specific order based on some criteria. In this case, the criteria is the index of letters, where each letter is assigned a numerical value, such as A being assigned the value 1 and B being assigned the value
2.
To achieve this sorting, you can use a function called
toSorted()
, which arranges the array elements according to their indices. The expected output for the given input array would be:To accomplish this, you can use a constant array months that contains the names of all twelve months of the year. By doing so, you can access each month’s index in the array, enabling you to sort the array according to the desired criteria.