About an array of scheduling problems

var arr = [5,1,3,7,0,9,4,2,6,8];

// 冒泡排序法
function arrsort(arr){
    var length = arr.length,temp;
    for(var i = 0; i < length - 1; i++){
        for(var j = 0; j < length - 1; j++){
            if (arr[j] > arr[j + 1]) {
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
    return arr;
};
// 冒泡排序法
console.log(arrsort(arr));
// sort()很复杂,还有参数作比较
console.log(arr.sort());
// 倒叙排序法
console.log(arr.reverse());

js with sort () method is an array sorted. sort () method has an optional parameter, is used to determine the function of the sequence of elements. If this parameter is omitted, the elements in the array are sorted in the order of ASCII characters. Such as:

var arr = ["a", "b", "A", "B"];
arr.sort();
console.log(arr);//["A", "B", "a", "b"]
因为字母A、B的ASCII值分别为65、66,而a、b的值分别为97、98,所以上面输出的结果是 ["A", "B", "a", "b"] 。

  如果数组元素是数字呢,结果会是怎样?

var arr = [15, 8, 25, 3];
arr.sort();
console.log(arr);//[15, 25, 3, 8]

The result is [15, 25, 3, 8]. In fact, sort method calls the toString () method for each item in the array, get the string, and then to sort the resulting string. Although the value 15 is larger than 3, but string comparisons to "15" is ranked "3" in front. Obviously, this result is not what we want, this time, the parameters sort () method to play a role, we put this parameter is called the comparison function.

Comparison function receives two parameters, the first parameter if the second should be located before a negative number is returned, if the parameters are equal Returns 0 if the first parameter should be located after the second return a positive number. example:

var arr = [23, 9, 4, 78, 3];
var compare = function (x, y) {//比较函数
    if (x < y) {
        return -1;
    } else if (x > y) {
        return 1;
    } else {
        return 0;
    }
}
console.log(arr.sort(compare));        

Results [3, 4, 9, 23, 78], to return the results we want. If you sort in descending order, the comparison function can be written like this:

var compare = function (x, y) {
    if (x < y) {
        return 1;
    } else if (x > y) {
        return -1;
    } else {
        return 0;
    }
}

We can not compare function to compare a sequence can not be converted into a string of numbers and figures:

var arr = ["b", 5];
console.log(arr.sort(compare))

The result is [ "b", 5]. Because the comparison function when compared to first string will be converted to digital, and then comparing the string b can not be converted to digital, so it can not be compared. However, when no comparison function compares the ASCII values, the result is [5, "b"].

Second, the sort an array of objects
  If the object is an array of items that we need to sort the array based on an attribute of an array of items, how to do it? In fact, and almost in front of the comparison function:

var arr = [{name: "zlw", age: 24}, {name: "wlz", age: 25}];
var compare = function (obj1, obj2) {
    var val1 = obj1.name;
    var val2 = obj2.name;
    if (val1 < val2) {
        return -1;
    } else if (val1 > val2) {
        return 1;
    } else {
        return 0;
    }            
} 
console.log(arr.sort(compare));

The output is [Object {name = "wlz", age = 25}, Object {name = "zlw", age = 24}], can be seen the array have been sorted by the name attribute. We can compare the above function and then transform the look:

var compare = function (prop) {
    return function (obj1, obj2) {
        var val1 = obj1[prop];
        var val2 = obj2[prop];if (val1 < val2) {
            return -1;
        } else if (val1 > val2) {
            return 1;
        } else {
            return 0;
        }            
    } 
}

If you want to sort by age, arr.sort (compare ( "age")) can be.

But note the age of the property to sort, if the value of the property is the digital age, then sort the result will be what we want. But many times we pass data back from the server, the attribute value is usually a string. Now I put the above array read:

var arr = [{name: " zlw", age: "24"}, {name: "wlz", age: "5"}];
see, I to the digital age attribute string, the second age value of the array item is changed to "5." After calling arr.sort (compare ( "age") ) Again, the result is:

[Object {name = "zlw" , age = "24"}, Object {name = "wlz", age = "5"}]
Our expectation is 25 5 in the front row, but the result is not. This is because when comparing the size of two numeric strings, they will compare the size of the ASCII value, the comparison rules are: starting with the first character, in turn backwards until the occurrence of different characters, different then the first ASCII value of the character size is determined. Therefore, the "24" and "5" when compared to the size of the first comparator "2" and "5" ASCII value, apparently "2" than the ASCII value of "5" is small, i.e., determine the sort order.

Now, we need to make some modifications to the comparison function:

var compare = function (prop) {
    return function (obj1, obj2) {
        var val1 = obj1[prop];
        var val2 = obj2[prop];
        if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
            val1 = Number(val1);
            val2 = Number(val2);
        }
        if (val1 < val2) {
            return -1;
        } else if (val1 > val2) {
            return 1;
        } else {
            return 0;
        }            
    } 
}

In the comparison function, the first comparison value into a digital property Number (val1) and through! IsNaN determination value after conversion (Number (val1)) is not a number (possibly NaN3), if the value after the digital conversion, after comparing the value of the conversion, so that you can get the results we want, and to call

arr.sort(compare("age")) 得到:
[Object { name="wlz", age="5"}, Object { name="zlw", age="24"}]

You can see, it is indeed sorted the right way up.

The article talked about are based, no technical content, but recently the project has encountered a problem on an array of objects to be sorted, so here write to share with you, I believe can help some friends.

Published 130 original articles · won praise 103 · views 260 000 +

Guess you like

Origin blog.csdn.net/xiaolinlife/article/details/97615030