Understanding of reduce, and several common application scenarios

1. Concept

reduce will traverse the array, and the two values ​​of the callback function respectively represent the cumulative result of the logical operation and the current value, which are often used to accumulate arrays, etc.

reduce function syntax

arr.reduce(function (previousValue, currentValue) { /* logical function */ }, initialValue) arr: means to traverse an array previousValue: the accumulation result of the array needs to be returned in the function body currentValue: the current value of the arr array Traversal item initialValue: Indicates the initial value, optional, if not filled, previousValue is the first item of the array, currentValue is the second item of the array; if filled, previousValue is initialValue, currentValue is the first item of the array.





2. Several common application scenarios

①. Accumulate and sum the array

  let arr = [1, 2, 3, 4, 5, 6]
        var sum = 0
        sum = arr.reduce(function (sum, cur) {
            sum += cur
            return sum
        }, 0)
        console.log(sum)

②, the sum of the values ​​in the object array

let arr2 = [{
                subject: '数学',
                marks: 78
            },
            {
                subject: '物理',
                marks: 80
            },
            {
                subject: '化学',
                marks: 93
            }
        ]
        let sum = 0
        sum = arr2.reduce(function (sum, cur) {
            sum += cur.marks
            return sum
        }, 0)
        console.log('分数之和是', sum)

③, flatten the array (convert multidimensional array to one-dimensional)

 let arr3 = [ [1,2], [3,4], [5,6], [7,8] , [9,10] ];
        let sum = []
        sum = arr3.reduce(function(sum,arr){
            // sum.push(...arr)两种都可以
            sum = sum.concat(arr)
            return sum
        },[])
        console.log(sum)

④. Group objects by attribute (scores greater than or equal to 50 points are passed, and those with scores lower than 50 points are not passed)

let arr3 = [{
                subject: '物理',
                marks: 41
            },
            {
                subject: '化学',
                marks: 59
            },
            {
                subject: '高等数学',
                marks: 36
            },
            {
                subject: '应用数学',
                marks: 90
            },
            {
                subject: '英语',
                marks: 64
            },
        ];
        let obj = {
            pass: [],
            fail: []
        }
        obj = arr3.reduce(function (obj, cur) {
            cur.marks >= 50 ? obj.pass.push(cur) : obj.fail.push(cur)
            return obj
        }, obj)
        console.log(obj)

⑤. Suppose set A={a, b}, set B={0, 1, 2}, then the Cartesian product of the two sets is {(a, 0), (a, 1), (a, 2) , (b, 0), (b, 1), (b, 2)}. Find the Cartesian product when A={a, b, …, n}, B={0, 1, 2, …, n}.

  let arr = [
            [{
                a: 1,
                b: 2
            }, 'c'],
            [1, 2, 3],
            [7, 8, 9]
        ]
        let arrs

        arr.reduce(function (sum, cur) {
            console.log(sum, 'sum-----')
            console.log(cur, 'cur-----')
            arrs = []
            for (var i = 0; i < sum.length; i++) {
                for (var j = 0; j < cur.length; j++) {
                    let temparr = []
                    console.log(Array.isArray(sum[i]))
                    Array.isArray(sum[i]) ? temparr = temparr.concat(sum[i]) : temparr.push(sum[i])
                    temparr.push(cur[j])
                    arrs.push(temparr)
                }
            }
            return arrs
        })
        console.log(arrs,'arrs------------')

Guess you like

Origin blog.csdn.net/qq_45791799/article/details/125426273