数组的操作

序号 操作 备注
1 获取数组最大(最小)值
2 获取数组最大值
3 获取数组最大值

  1. 获取数组最大(最小)值

    Math.max(...arr1) 和 Math.min(...arr1) 方法

    
    let arr1 = [8, 4, 7, '52', 6, 9, 3, '2']
    let maxNumber = Math.max(...arr1)
    let minNumber = Math.min(...arr1)
    console.log('最大值:', maxNumber);// 52
    console.log('最小值:', minNumber);// 2
                

    arr2.reduce 方法

      
    let arr2 = [
        {
          age: "12",
          name: "张三",
        }, {
          age: 46,
          name: "李四",
        }, {
          age: 8,
          name: "王五",
        },
        {
          age: "34",
          name: "赵六",
        },
    ]
    let bigest = arr2.reduce((p, v) => p.age < v.age ? v : p)
    let smallest = arr2.reduce((p, v) => p.age > v.age ? v : p)
    let totalAge = arr2.reduce((accumulator, currentValue, currentIndex, array) => {
        	return accumulator + parseFloat(currentValue.age)
    }, 0)
    console.log('最大值:', bigest); //  {age: 46, name: "李四"}
    console.log('最小值:', smallest); //  {age: 8, name: "王五"}
    console.log('年龄总的加起来:', parseFloat(totalAge).toFixed(2)); // 100.00
                

    arr3.sort(compare) 方法

      
    function compare(a, b) {
        return a - b ;//升序
        // return b - a ;//降序
    }
    let arr3 = [5, 24, 32, '14', 6, '6', 14]
    let _arr3 = arr3.sort(compare)
    console.log('排序:_arr3 :', _arr3)
    console.log('最小值 :', _arr3[0], '】【最大值 :', _arr3[_arr3.length - 1])
                

    compare(property) 对象内的值 比较

    
    let arr_3 = [{
            age: "12",
            name: "张三",
        }, {
            age: 46,
            name: "李四",
        }, {
            age: 8,
            name: "王五",
        },
        {
            age: "34",
            name: "赵六",
        },
    ]
    

    function compare(property) {
    return function(a, b) {
    return a[property] - b[property]; //升序
    // return b[property] - a[property]; //降序
    }
    }
    let _arr_3 = arr_3.sort(compare('age'))
    console.log('_arr_3:', _arr_3)
    /*
    0: {age: 8, name: "王五"}
    1: {age: "12", name: "张三"}
    2: {age: "34", name: "赵六"}
    3: {age: 46, name: "李四"}
    */