Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

reduce的几种用法 #24

Open
leefinder opened this issue Feb 19, 2020 · 0 comments
Open

reduce的几种用法 #24

leefinder opened this issue Feb 19, 2020 · 0 comments

Comments

@leefinder
Copy link
Owner

求最大子集

const subcollection = (arr) => arr.reduce((t, v) => t.concat(t.map(item => item.concat(v))), [[]])
subcollection([1, 2, 3]) // [] [1] [2] [1, 2] [3] [1, 3] [2, 3] [1, 2, 3]

累加

const Accumulation = (...nums) => nums.reduce((t, v) => t + v, 0)

Accumulation(1, 2, 3, 4, 5); // 15

累乘

const Multiplication = (...nums) => nums.reduce((t, v) => t * v, 1)

Multiplication(1, 2, 3, 4, 5); // 120

实现数组reverse

const Reverse = (arr = []) => arr.reduceRight((t, v) => (t.push(v), t), [])

Reverse([1, 2, 3, 4, 5]); // [5, 4, 3, 2, 1]

reduce实现map

[1, 2, 3, 4].map(t => t * 2)
[1, 2, 3, 4].reduce((t, v) => [...t, t * 2], [])

##reduce实现filter

[1, 2, 3, 4].filter(t => t > 2)
[1, 2, 3, 4].reduce((t, v) => t > 2 ? [...t, v] : t, [])

reduce实现some

[1, 2, 3, 4].some(t => t > 2)
[1, 2, 3, 4].reduce((t, v) => t || v > 2, false)

reduce实现every

[1, 2, 3, 4].every(t => t > 2)
[1, 2, 3, 4].reduce((t, v) => t && v > 2, true)

数组分割

const Chunk = (arr, size) => arr.length > 0 ? arr.reduce((t, v) => (t[t.length - 1].length === size ? t.push([v]) : t[t.length - 1].push(v), t), [[]]) : []
Chunk([1, 2, 3, 4, 5, 6, 7, 8, 9], 2) // [[1, 2], [3, 4], [5, 6], [7, 8], [9]]

数组过滤

const Difference = (arr1, arr2) => arr1.reduce((t, v) => (!arr2.includes(v) && t.push(v), t), [])
Difference([1, 2, 3, 4], [3, 4, 5]) // [1, 2] 

数组填充

const Fill = (arr, start, end, text) => {
    if (start < 0 || start >= end || end > arr.length) return arr;
    return [
        ...arr.slice(0, start),
        ...arr.slice(start, end).reduce((t, v) => (t.push(text || v), t), []),
        ...arr.slice(end, arr.length)
    ]
}  
const arr = [0, 1, 2, 3, 4, 5, 6];
Fill(arr, 'aaa', 2, 5); // [0, 1, 'aaa', 'aaa', 'aaa', 5, 6]

数组拍平

const Flat = arr => arr.reduce((t, v) => t.concat(Array.isArray(v) ? Flat(v) : v), [])
Flat([[1,2,3], [4,5], [5,6, [7, 8]]]) // [1, 2, 3, 4, 5, 6, 7, 8]

数组去重

const Dupli = arr => arr.reduce((t, v) => (!t.includes(v) && t.push(v), t), [])
Dupli([1,2,1,2,3,4,5]) // [1, 2, 3, 4, 5]

参考链接

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant