Recommendation 11: Enhanced sorted array sort function

  The method not only sort alphabetically sorted, this time would have to provide a comparison function for the method operations performed in other sequences, to compare the two function values, and then returns a view for explaining the relative order of these two worthy . digital comparator function should have two parameters a and b, the return value is as follows:

  1. If the value of the custom criteria, a is less than b, in a sorted array should appear before b, it returns a value less than 0 according to the
  2. If a is equal to b, returns 0
  3. If a than b, that returns a value greater than zero

  The following example, according to the comparison function to compare the size of each element of the array, and press the ascending sort order

function f(a,b){
  return (a-b)
}
var a = [4,3,5,6,7,3,6,8]
a.sort(f)
console.log(a); //[3, 3, 4, 5, 6, 6, 7, 8]

If you are descending, so that the return value is negated like

function f(a,b){
  return -(a-b)
}
var a = [4,3,5,6,7,3,6,8]
a.sort(f)
console.log(a);  //[8, 7, 6, 6, 5, 4, 3, 3]

(1) The arrangement of the array parity value

  Usage sort method more flexible, but is more flexible design of the comparison function, for example: an array arrangement according to the number of parity sequence, only two comparison function determines whether the number of the parity parameter, and decides the order

function f(a,b){
  var a = a%2
  var b = b%2
  if(a==0) return 1
  if(b==0) return -1
}


var a = [3,1,2,4,5,7,6,8,0,9]
a.sort(f)
console.log(a);  //[3, 1, 5, 7, 9, 0, 8, 6, 4, 2]

  sort comparison function when calling the method, the value of each element is passed to the comparison function, if the element is even, then retain its position does not move, if the element is an odd number, the parameters a and b in the display sequence are interchanged, in order to achieve an array All elements of the parity sort.

(2) case-insensitive string sorting

If you do not want to differentiate between the size of letters, uppercase and lowercase letters that is arranged in the same order

function f(a,b){
  var a = a.toLowerCase;
  var b= b.toLowerCase;
  if(a<b){
    return 1
  }else{
    return -1
  }
}
var  a = ['aB','Ab','Ba','bA']
a.sort(f)
console.log(a);  // ["aB", "Ab", "Ba", "bA"]

(3) the arrangement of separate floating point and integer

function f(a,b){
  if(a>Math.floor(a)){
    return 1
  }
  if(b>Math.floor(b)){
    return -1
  }
}

var a  = [3.555,3,2.111,5,7,3]
a.sort(f)
console.log(a);  //[3, 5, 7, 3, 2.111, 3.555]

Guess you like

Origin www.cnblogs.com/chorkiu/p/12092771.html