To sort an array in JavaScript, you can use the sort()
method. This method sorts the elements in the array in place and returns the sorted array. By default, it sorts the elements in ascending order according to their Unicode code points.
Here's an example of using the sort()
method to sort a simple array of numbers:
index.tsx72 chars3 lines
As you can see, the sort()
method has sorted the numbers in ascending order.
You can also pass a function as an argument to the sort()
method to specify a custom sorting order. The function should take two arguments, which represent consecutive elements in the array, and return a number that indicates their relative order.
Here's an example of using a custom sorting function to sort an array of objects based on a specific property:
index.tsx283 chars15 lines
In this example, the sorting function compares the age
properties of the objects and returns a negative number if a
should come before b
, a positive number if a
should come after b
, or 0 if their order doesn't matter.
gistlibby LogSnag