//求数组里1出现的次数

let arr = [1, 1, 2, 21, 1, 1, 3, 34, 44, 21]

    function arrayCount(array, item) {
        return array.reduce((total, cur) => {
            total += item == cur ? 1 : 0;
            return total
        }, 0)
    }
    console.log(arrayCount(arr, 1))

// 求数组对象最大值

    let cart = [
        { name: 'iphone12', price: 12000 },
        { name: 'mac', price: 25000 },
        { name: 'ipad', price: 5000 },
    ]

    function MaxPrice(goods) {
        return cart.reduce((pre, cur) => {
            return pre.price > cur.price ? pre : cur
        })
    }
    console.log(MaxPrice(cart))
    //或者Math.max.apply(Math, cart.map(item => item.price))
    // console.log(Math.max.apply(Math, cart.map(item => item.price)))

//求和

    function sum(goods) {
        return goods.reduce((total, cur) => {
            return (total += cur['price'])
        }, 0)
    }
    console.log(sum(cart))

es6数组排序

data.sort(function (a, b) { return a.value - b.value; })

降序

data.sort(function (a, b) { return b.value - a.value; })

文档更新时间: 2021-11-04 11:56   作者:admin