当前位置:网站首页>10 reduce common "tricks"
10 reduce common "tricks"
2022-06-24 13:35:00 【51CTO】
I don't know what people usually use Reduce Not much , I don't use much of this melon anyway . But actually ,Reduce What can be done , Much more than we can think of , This article brings 10 individual Reduce Common scenarios and techniques , There must be something you don't know ~
blunt ヾ(◍°∇°◍)ノ゙

Add up / The cumulative
Cumulatively, we are probably the most familiar Reduce A usage of , besides , It can also be used for accumulation .
Ask for the biggest / minimum value
If you use native api Ask for the biggest / minimum value , it ,Reduce The same effect can be achieved .
Format search parameters
obtain url The parameter on is a requirement we often face , use forEach Traversal can , use Reduce Accumulation can be more , This reduces the number of declarations query object .
Deserialize search parameters
With access url Parameters , You can re hang the parameters to url above , To use , Collection .
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.
Flatten nested arrays
We all use .flat(Infinity) Infinitely flatten all multidimensional arrays into one-dimensional arrays , Only reduce and flat This is also possible .
Realization flat
If you want to achieve flat, use reduce That's right , Another handwritten native api Internal implementation , Well done just .
// 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.
Array weight removal
Array weight removal , use reduce It can be , It is written as follows :
Array count
Count the items of the array , Return to one map, Is the number of repetitions of each item ,reduce One line of code , Collection !
Get multiple properties of the object
Get multiple properties of an object , Then assign to the new object , The stupid way is as follows :
// 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.
use Reduce Solve it like this , It seems a lot wiser :
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 string
except reverse Flip the array ,Reduce It's fine too , Plus split, You can reverse the string .
This article is generally translated from : medium.com/javascript-…
author : fatfish
OK, The above is the sharing of this article . Like, follow the comments , Help good writing
I'm Anthony nuggets 100 Popular front-end technology bloggers with a reading volume of 10000 INFP Writing personality persistence 1000 Japanese Geng Wen Pay attention to me , Spend the long programming years with you
边栏推荐
- 天猫618农产品“百强县” 35个县域来自中西部及东北
- Use abp Zero builds a third-party login module (I): Principles
- MySQL interview questions
- The agile way? Is agile development really out of date?
- 3. Caller 服务调用 - dapr
- Getting started with the lvgl Library - colors and images
- Richard Sutton, the father of reinforcement learning, paper: pursuing a general model for intelligent decision makers
- Geological disaster early warning monitoring RTU
- Opengauss kernel: simple query execution
- CVPR 2022 | interprétation de certains documents de l'équipe technique de meituan
猜你喜欢

Who is the fish and who is the bait? Summary of honeypot recognition methods from the perspective of red team

我从根上解决了微信占用手机内存问题

"Interesting" is the competitiveness of the new era

The data value reported by DTU cannot be filled into Tencent cloud database through Tencent cloud rule engine

YOLOv6:又快又准的目标检测框架开源啦

I have fundamentally solved the problem of wechat occupying mobile memory

Kubernetes cluster deployment

不用Home Assistant,智汀也开源接入HomeKit、绿米设备?

面试官:MySQL 数据库查询慢,除了索引问题还可能是什么原因?

CVPR 2022 - Interpretation of selected papers of meituan technical team
随机推荐
hands-on-data-analysis 第三单元 模型搭建和评估
Coinbase will launch the first encryption derivative for individual investors
#云原生征文#Ingress案例实战
强化学习之父Richard Sutton论文:追寻智能决策者的通用模型
The second phase of freshman engineering education seminar is to enroll in the China 100 school peer program
Use terminal to activate CONDA service in pypharm (the ultimate method is definitely OK)
TCP triple handshake
I enlighten a friend and my personal understanding of the six patriarchs' Tan Jing
Use abp Zero builds a third-party login module (I): Principles
kotlin 语言特性
Introduction to reptile to give up 01: Hello, reptile!
发扬连续作战优良作风 全力以赴确保北江大堤安全
金鱼哥RHCA回忆录:DO447管理清单和凭据--为访问清单主机创建机器凭据
YOLOv6:又快又准的目标检测框架开源啦
Opengauss kernel: simple query execution
Without home assistant, zhiting can also open source access homekit and green rice devices?
CVPR 2022 | interprétation de certains documents de l'équipe technique de meituan
Hands on data analysis unit 3 model building and evaluation
LVGL库入门教程 - 颜色和图像
About the hacked database