map、filter、reduce函数用法简单示例

php中的map、filter、reduce函数使用

有时候真的很头疼php中参数的位置,经常记错

$arr = [1, 2, 3, 4, 5];

// array_map — 为数组的每个元素应用回调函数
$arr_new = array_map(function ($val) {
    return $val + 3;
}, $arr);
var_dump($arr_new); //[4,5,6,7,8]

// array_filter — 使用回调函数过滤数组的元素
$arr1 = array_filter($arr, function ($val) {
    return $val % 2 == 0;
});
var_dump($arr1); //[2,4]


function sum($carry, $item)
{
    return $carry + $item;
}
function product($carry, $item)
{
    return $carry * $item;
}
// array_reduce — 用回调函数迭代地将数组简化为单一的值,第三个参数为初始值
var_dump(array_reduce($arr, "sum")); // int(15)
var_dump(array_reduce($arr, "product", 10)); // int(1200)
var_dump(array_reduce([], "sum", 10)); // int(10) 数组为空,返回初始值,若未指定 initial 参数则返回 null。

js中的map、filter、reduce方法使用

 // reduce() 方法接收一个函数作为累积器, 数组中的每个值( 从左到右) 开始缩减, 最终为一个值。
    const arr = [1, 2, 3, 4, 5];
    const init_val = 3;
    const sum = arr.reduce((carry, currVal, currentIndex, arr) => {
        return carry + currVal;
    }, init_val);
    console.log(sum) //18

    //二维数组转换成一维数组
    const values = [
        [2, 3, 5],
        [1, 2, 4],
        [8, 5, 5]
    ]
    const values_arr = values.reduce((carry, current) => carry.concat(current));
    console.log(values_arr) //[2, 3, 5, 1, 2, 4, 8, 5, 5]

    //处理字符串
    const func_arr = [String.prototype.trim, String.prototype.toUpperCase];
    const str = func_arr.reduce((carry, func) => func.call(carry), ' hello ');
    console.log(str) //HELLO

    //使用自定义函数
    const func_arr1 = [
        (val) => val * 2,
        (val) => val + 5,
    ];
    const res = func_arr1.reduce((carry, func) => func(carry), 2);
    console.log(res) //9

    const colors = ['green', 'red', 'red', 'yellow', 'red', 'yellow', 'green', 'green'];
    const colors_num = colors.reduce((carry, color) => {
        carry[color] = color in carry ? carry[color] + 1 : 1
        return carry;
    }, {});
    console.log(colors_num); // {green: 3, red: 3, yellow: 2}

    // filter方法
    const colors_new = colors.filter((value, i) => {
        return value != 'green'
    })
    console.log(colors_new) //['red', 'red', 'yellow', 'red', 'yellow']

    //map方法
    const colors_obj_arr = colors.map((value, i) => {
        return {
            'color': value,
            'order': i
        }
    })
    console.log(colors_obj_arr)

 

posted @ 2024-01-31 15:02  carol2014  阅读(5)  评论(0编辑  收藏  举报