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

Tips on using reduce (code example)

不言
Release: 2019-03-18 10:29:33
forward
1979 people have browsed it

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
    })
Copy after login

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)
    },[])
Copy after login

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
    },{})
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template