当前位置:网站首页>10 个 Reduce 常用“奇技淫巧”
10 个 Reduce 常用“奇技淫巧”
2022-06-24 12:50:00 【51CTO】
不知道大家平常用 Reduce 多不多,反正本瓜用的不多。但实际上,Reduce 能做的,比我们能想到的要多得多,本篇带来 10 个Reduce 常用场景和技巧,一定有你不知道~
冲ヾ(◍°∇°◍)ノ゙

累加/累积
累加我们可能是最熟悉 Reduce 的一种用法,除此之外,还可以用做累积。
求最大/最小值
如果你用原生 api 求最大/最小值,无可厚非,Reduce 也能实现同样的效果。
格式化搜索参数
获取 url 上的参数是我们经常面临的需求,用 forEach 遍历可以,用 Reduce 累加更可以,这样可以减少声明 query 对象。
反序列化搜索参数
有了获取 url 参数,就有把参数重新挂在到 url 上面,好用,收藏。
const stringifySearch = (search = {}) => {
return Object.entries(search)
.reduce(
(t, v) => `${t}${v[0]}=${encodeURIComponent(v[1])}&`,
Object.keys(search).length ? "?" : ""
)
.replace(/&$/, "");
};
const search = stringifySearch({
name: "fatfish",
age: 100,
});
const link = `https://medium.com/${search}`;
console.log(link); // https://medium.com/?name=fatfish&age=100
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
拉平嵌套数组
我们都会用 .flat(Infinity) 无限拉平所有多维数组成一维数组,只用 reduce 和 flat 也是可以做到这一点的。
实现 flat
如果想实现 flat,用 reduce 没错了,又是一个手写原生 api 内部实现,妥妥的刚。
// Expand one layer by default
Array.prototype.flat2 = function (n = 1) {
const len = this.length
let count = 0
let current = this
if (!len || n === 0) {
return current
}
// Confirm whether there are array items in current
const hasArray = () => current.some((it) => Array.isArray(it))
// Expand one layer after each cycle
while (count++ < n && hasArray()) {
current = current.reduce((result, it) => {
result = result.concat(it)
return result
}, [])
}
return current
}
const array = [ 1, [ 2, [ 3, [ 4, [ 5 ] ] ] ] ]
// Expand one layer
console.log(array.flat()) // [ 1, 2, [ 3, [ 4, [ 5 ] ] ] ]
console.log(array.flat2()) // [ 1, 2, [ 3, [ 4, [ 5 ] ] ] ]
// Expand all
console.log(array.flat(Infinity))
console.log(array.flat2(Infinity))
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
数组去重
数组去重,用 reduce 竟然也可以,写法如下:
数组计数
将数组的项进行计数,返回一个 map,分别是每个项重复的次数,reduce 一行代码搞定,收藏!
获取对象多个属性
获取对象的多个属性,然后赋给新的对象,比较笨的做法如下:
// There is an object with many properties
const obj = {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5
// ...
}
// We just want to get some properties above it to create a new object
const newObj = {
a: obj.a,
b: obj.b,
c: obj.c,
d: obj.d
// ...
}
// Do you think this is too inefficient?
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
用 Reduce 这样解决,就显得明智了许多:
const getObjectKeys = (obj = {}, keys = []) => {
return Object.keys(obj).reduce((acc, key) => (keys.includes(key) && (acc[key] = obj[key]), acc), {});
}
const obj = {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5
// ...
}
const newObj = getObjectKeys(obj, [ 'a', 'b', 'c', 'd' ])
console.log(newObj)
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
反转字符串
除了 reverse 做数组的翻转,Reduce 也可以,再加上 split,就可以反转字符串啦。
本篇通译自: medium.com/javascript-…
作者: fatfish
OK,以上便是本篇分享。点赞关注评论,为好文助力
我是掘金安东尼 100 万阅读量人气前端技术博主 INFP 写作人格坚持 1000 日更文 关注我,陪你一起度过漫长编程岁月
边栏推荐
- 如何化解35岁危机?华为云数据库首席架构师20年技术经验分享
- Baidu simian: talk about persistence mechanism and rdb/aof application scenario analysis!
- 手把手教你用AirtestIDE无线连接手机!
- Geological disaster early warning monitoring RTU
- 39 - read XML node and attribute values
- 实现领域驱动设计 - 使用ABP框架 - 更新操作实体
- Yolov6: the fast and accurate target detection framework is open source
- 系统测试主要步骤
- 青藤入选工信部网安中心“2021年数字技术融合创新应用典型解决方案”
- 问个sql view的问题
猜你喜欢

‘高并发&高性能&高可用服务程序’编写及运维指南

Opengauss kernel: simple query execution

The agile way? Is agile development really out of date?

Use abp Zero builds a third-party login module (I): Principles

Definition and use of constants in C language

Nifi from introduction to practice (nanny level tutorial) - environment

Use abp Zero builds a third-party login module (I): Principles

CVPR 2022 | 美團技術團隊精選論文解讀

DTU上报的数据值无法通过腾讯云规则引擎填入腾讯云数据库中

Kubernetes cluster deployment
随机推荐
Express 100 Express query interface (API) interface specification document - detailed version
物联网?快来看 Arduino 上云啦
AGCO AI frontier promotion (6.24)
使用 Abp.Zero 搭建第三方登录模块(一):原理篇
#yyds干货盘点# 解决剑指offer:调整数组顺序使奇数位于偶数前面(二)
Internet of things? Come and see Arduino on the cloud
[one picture series] one picture to understand Tencent Qianfan apaas
ERR AUTH&lt; password&gt; called without anypassword configured for the default user. Ar
我从根上解决了微信占用手机内存问题
#云原生征文#Ingress案例实战
如何避免严重网络安全事故的发生?
系统测试主要步骤
问个sql view的问题
Can inspection results be entered after the completion of inspection lot UD with long-term inspection characteristics in SAP QM?
3. caller service call - dapr
CVPR 2022 - Interpretation of selected papers of meituan technical team
Attack Science: ARP attack
Sphere, openai and ai21 jointly publish the best practice guidelines for deployment models
Integrated API interface code of domestic express companies for intra city distribution and ordering - Express 100
CVPR 2022 | 美團技術團隊精選論文解讀