2rever的前端小站

数组对象的排序

Word count: 213 / Reading time: 1 min
2018/11/21 Share
  • 数组对象的排序
    因为最近工作遇到要对数组对象进行排序,所以根据冒泡排序进行修改,实现对简单数组对象的排序
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    function sortArray(array, val, order = "up") {
    for (var i = 0; i < array.length; i++) {
    for (var k = 0; k < array.length - i - 1; k++) {
    if (array[k][val] > array[k + 1][val]) {
    var temp = array[k]
    array[k] = array[k + 1]
    array[k + 1] = temp
    }
    }
    }
    return order == "up" ? array : sortReverse(array)
    }



    function sortReverse(array) {
    let len = array.length / 2 | 0
    let temp
    for (var i = 0, k = array.length - 1; i < len; i++, k--) {
    temp = array[i]
    array[i] = array[k]
    array[k] = temp
    }
    return array
    }


    var arr = [{
    name: 'zopp',
    age: 79
    },
    {
    name: 'gpp',
    age: 35
    },
    {
    name: 'yjj',
    age: 8
    },
    {
    name: 'zopp',
    age: 48
    },
    {
    name: 'gpp',
    age: 66
    },
    {
    name: 'yjj',
    age: 7
    },
    ];
CATALOG