JavaScript : Sorting Arrays

Sorting arrays in JavaScript is a common operation that can be accomplished using various methods. Here are some common techniques for sorting arrays:

1. sort()


The sort() method sorts the elements of an array in place and returns the sorted array. By default, it sorts the elements as strings.


let fruits = ['banana', 'apple', 'orange', 'grape'];
fruits.sort();
console.log(fruits); // Output: ['apple', 'banana', 'grape', 'orange']

 

 2. Custom Sorting with sort()


You can provide a custom comparison function to the sort() method to specify how to sort elements.


let numbers = [10, 5, 20, 2, 15];
numbers.sort((a, b) => a - b); // Ascending order
console.log(numbers); // Output: [2, 5, 10, 15, 20]

numbers.sort((a, b) => b - a); // Descending order
console.log(numbers); // Output: [20, 15, 10, 5, 2]

 

3. reverse()


The reverse() method reverses the order of the elements in an array.


let fruits = ['banana', 'apple', 'orange', 'grape'];
fruits.reverse();
console.log(fruits); // Output: ['grape', 'orange', 'apple', 'banana']

 

 4. Sorting Objects by Property


You can sort an array of objects based on a specific property using the sort() method with a custom comparison function.


let people = [
  { name: 'John', age: 30 },
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 35 }
];

people.sort((a, b) => a.age - b.age);
console.log(people);
/* Output:
[
  { name: 'Alice', age: 25 },
  { name: 'John', age: 30 },
  { name: 'Bob', age: 35 }
]
*/

 

5. Sorting with localeCompare()


For sorting strings in a locale-sensitive manner, you can use the `localeCompare()` method.


let fruits = ['banane', 'apfel', 'orange', 'grape'];
fruits.sort((a, b) => a.localeCompare(b, 'de'));
console.log(fruits); // Output: ['apfel', 'banane', 'grape', 'orange']

 

These methods provide different ways to sort arrays in JavaScript based on various criteria. Depending on your specific requirements, you can choose the appropriate method or combination of methods to sort arrays efficiently.

AI car modification · buy quality backlinks · guest post service · link building service · link building service · buy backlinks · SEO, GEO, AEO, AIO and LLMO · Bedeutung von Backlinks für Google · winandoffice · aiswapface photo face swap · dofollow backlinks · link building service · guest post service · quality backlinks · guest post service · dofollow backlinks · link building service · dofollow backlinks · buy backlinks · buy quality backlinks · dofollow backlinks · dofollow backlinks · link building service · hacklink satın al · Contextual backlinks: judge the paragraph and destination together · hacklink · hacklink satın al · hacklink panel satın al · jojobet · hacklink satın al · jojobet · jojobet · jojobet · jojobet · jojobet · jojobet · jojobet · jojobet · jojobet · jojobet · jojobet giriş · jojobet güncel · jojobet · jojobet · jojobet · jojobet