sort an array in javascript

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.tsx
let numbers = [5, 2, 9, 1, 5, 6];
numbers.sort(); // [1, 2, 5, 5, 6, 9]
72 chars
3 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.tsx
let people = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 20 },
];

people.sort((a, b) => a.age - b.age); // sorted by age in ascending order
/*
[
  { name: 'Charlie', age: 20 },
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
]
*/
283 chars
15 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.

related categories

gistlibby LogSnag