reduce使用场景记录
2023-03-20 本文已影响0人
江湖小盛
// 求和
const arr1 = [1, 2, 3]
const delTotal = arr1.reduce((acc, cur) => {
return acc + cur
}, 0)
// 求最大值
const delMax = arr1.reduce((acc, cur) => {
return Math.max(acc, cur)
}, 0)
// 将二维数组转化为一维
const arr2 = [[1, 2, 3], [4, 5, 6]]
const delFlat = arr2.reduce((acc, cur) => {
return [...acc, ...cur]
}, [])
// 数组去重
const arr3 = [1, 2, 3, 2, 5, 1]
const delRepeat = arr3.reduce((acc, cur) => {
return acc.includes(cur) ? acc : acc.concat(cur)
}, [])
// 组合对象
// https://xxx.com/369991562?age=20&name=zhang
const getSearchParams = () => {
const searchPar = window.location.search
const queryStr = searchPar.split('?')[1]
const queryList = queryStr.split('&')
return queryList.reduce((acc, cur) => {
const tempArr = cur.split('=')
return {
...acc,
[tempArr[0]]: decodeURI(tempArr[1])
}
}, {})
}
// 数组分组
const people = [
{ name: 'Alice', gender: 'female' },
{ name: 'Bob', gender: 'male' },
{ name: 'Charlie', gender: 'male' },
{ name: 'Diana', gender: 'female' }
]
const groups = people.reduce((acc, curr) => {
const key = curr.gender
if (!acc[key]) {
acc[key] = []
}
acc[key].push(curr)
return acc
}, {})
// 对象筛选
const testMap = {
'test1': '测试1',
'test2': '测试2'
}
const dataTest = {
'test1': [{ name: 'zhangsan', age: 20 }],
'test2': [{ name: 'lisi', age: 30 }],
'test3': [{ name: 'wangwu', age: 40 }]
}
const dataKeys = Object.keys(dataTest)
const resultData = Object.keys(testMap).reduce((acc, curr) => {
if (dataKeys.includes(curr)) {
acc[curr] = dataTest[curr]
}
return acc
}, {})