Home  >  Article  >  Web Front-end  >  Tips on using reduce (code example)

Tips on using reduce (code example)

不言
不言forward
2019-03-18 10:29:331915browse

This article brings you the usage skills (code examples) of reduce. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

reduce

The array method has two parameters callback function callback and initialValue
The callback has four parameters prev, next, index, arr
initialValue: optional parameters, As the first prev of callback;
If initialValue is passed:
prev is initialValue for the first time, and then it is the return value.
next is each item of the array
index is the subscript of the array
arr is the original array
If initialValue is not passed:
prev is the first item of the array for the first time, and then it is return value.
next is each item starting from the second item of the array
index, arr are not affected

Underscore to camel case

    let str = "my_name_is_sxq";
    let result = str.split('').reduce((p,n,i,arr)=>{
        if(n=='_'){
            arr[i+1] = arr[i+1].toUpperCase()
            return p
        }
        return p + n
    })

Array flattening

    // 二维转一维
    let arr = [1,2,3,[4,5],[6,7,[8,9]]];
    let newarr = arr.reduce(function(prev,next){
        return Array.isArray(next)?prev=prev.concat(...next):prev=prev.concat(next)
    },[])

Array to object

    // 路由数组转对象
    let arr = [{path:'/',component:function(){}},{path:'/user',component:function(){}}]
    let result = arr.reduce((memo,current)=>{
        memo[current.path] = current.component
        return memo
    },{})

The above is the detailed content of Tips on using reduce (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete