Detailed explanation of sorting method of array Array. sort of in JavaScript

• 2021-07-24 10:10:14
• OfStack

The sort () method of an array in JavaScript is primarily used to sort the elements of the array. The sort () method has one optional parameter. However, this parameter must be a function. When an array calls the sort () method, the elements in the array are sorted alphabetically (in character encoding order) if no arguments are passed. If you want to sort according to other criteria, you need to pass a parameter as a function that compares two values and returns a number indicating the relative order of the two values.

1. Sort the number array from small to large.

Code:

var arr = [22,12,3,43,56,47,4];
arr.sort();
console.log(arr); // [12, 22, 3, 4, 43, 47, 56]
arr.sort(function (m, n) {
if (m < n) return -1
else if (m > n) return 1
else return 0
});
console.log(arr); // [3, 4, 12, 22, 43, 47, 56]

2. Perform case-insensitive alphabetical sorting of string arrays.

Code:

var arr = ['abc', 'Def', 'BoC', 'FED'];
console.log(arr.sort()); // ["BoC", "Def", "FED", "abc"]
console.log(arr.sort(function(s, t){
var a = s.toLowerCase();
var b = t.toLowerCase();
if (a < b) return -1;
if (a > b) return 1;
return 0;
})); // ["abc", "BoC", "Def", "FED"]

3. To sort the array containing objects, it is required to arrange them in the order from big to small according to the age in the objects

Code:

var arr = [{'name': ' Zhang 3', age: 26},{'name': ' Li 4', age: 12},{'name': ' Wang 5', age: 37},{'name': ' Zhao 6', age: 4}];
var objectArraySort = function (keyName) {
return function (objectN, objectM) {
var valueN = objectN[keyName]
var valueM = objectM[keyName]
if (valueN < valueM) return 1
else if (valueN > valueM) return -1
else return 0
}
}
arr.sort(objectArraySort('age'))
console.log(arr) // [{'name': ' Wang 5', age: 37},{'name': ' Zhang 3', age: 26},{'name': ' Li 4', age: 12},{'name': ' Zhao 6', age: 4}]

Related articles: