Home  >  Article  >  Web Front-end  >  JavaScript custom array sorting method_javascript skills

JavaScript custom array sorting method_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:14:151463browse

The example in this article describes the JavaScript custom array sorting method. Share it with everyone for your reference. The specific analysis is as follows:

Array has its own sorting function, which is more convenient to use. One thing we must be clear about is the basis for sorting. If sort does not pass in parameters, it will be sorted according to the order of character encoding (Unicode encoding).

var a=["3","2","1"]; 
console.log(a[0].charCodeAt(0)); // 51 
console.log(a[1].charCodeAt(0)); // 50 
console.log(a[2].charCodeAt(0)); // 49 
console.log(a.sort());      // ["1", "2", "3"] 
 
var a=["3","你","他"]; 
console.log(a[0].charCodeAt(0)); // 51 
console.log(a[1].charCodeAt(0)); // 20320 
console.log(a[2].charCodeAt(0)); // 20182 
console.log(a.sort());      // ["3", "他", "你"] 
 
var a=["3","11","222"]; 
console.log(a.sort());// ["11", "222", "3"]  
           // 多个字符的时候按照第一个字符的编码

But I think the most useful thing about sort is that you can customize the sorting. This is also common in practical applications, such as sorting an object array. For example, if you want to sort an object array in a linear plane according to a certain field in it, you can certainly write a function to do it yourself, but I don't think it is as convenient as sort.

var list = [ 
  { 
    max:3, 
    avg:2, 
    min:1 
  }, 
  { 
    max:10, 
    avg:15, 
    min:20 
  }, 
  { 
    max:8, 
    avg:5, 
    min:2 
  } 
]; 
// 根据max字段对list对象进行排序,从小到大的顺序 
// x,y就是要比较的数组的单个元素,这里就是list中的一个元素 
// 排序方法主要是要提供一个比较大小的规则,换句话说也就是要说明谁大谁小 
// 返回值为true or false 
function sortByField(x, y) { 
  return x.max - y.max; 
} 
console.log(list.sort(sortByField));

The operation effect is as shown below:

I hope this article will be helpful to everyone’s JavaScript programming design.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn