当前位置:网站首页>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
边栏推荐
- Cmput 379 explanation
- kotlin 协程 lanch 详解
- Without home assistant, zhiting can also open source access homekit and green rice devices?
- Getting started with the go Cobra command line tool
- Golden age ticket: Web3.0 Security Manual
- Hands on data analysis unit 3 model building and evaluation
- AGCO AI frontier promotion (6.24)
- Why did the audio and video based cloud conference usher in a big explosion of development?
- Opengauss kernel: simple query execution
- 青藤入选工信部网安中心“2021年数字技术融合创新应用典型解决方案”
猜你喜欢
Without home assistant, zhiting can also open source access homekit and green rice devices?
一文理解OpenStack网络
Comparator sort functional interface
Detailed explanation of abstractqueuedsynchronizer, the cornerstone of thread synchronization
LVGL库入门教程 - 颜色和图像
快速了解常用的消息摘要算法,再也不用担心面试官的刨根问底
CVPR 2022 | 美团技术团队精选论文解读
Getting started with the go Cobra command line tool
谁是鱼谁是饵?红队视角下蜜罐识别方式汇总
首席信息安全官仍然会犯的漏洞管理错误
随机推荐
Resolve symbol conflicts for dynamic libraries
开发者调查:Rust/PostgreSQL 最受喜爱,PHP 薪水偏低
How to create a new empty branch in the web development process of easyrtc?
16 safety suggestions from metamask project to solid programmers
天猫618农产品“百强县” 35个县域来自中西部及东北
Use terminal to activate CONDA service in pypharm (the ultimate method is definitely OK)
One article explains R & D efficiency! Your concerns are
10 个 Reduce 常用“奇技淫巧”
Without home assistant, zhiting can also open source access homekit and green rice devices?
Getting started with the go Cobra command line tool
I have fundamentally solved the problem of wechat occupying mobile memory
About the hacked database
Yyds dry goods counting solution sword finger offer: adjust the array order so that odd numbers precede even numbers (2)
Redis scenario
数据科学家面临的七大挑战及解决方法
What should I do if I fail to apply for the mime database? The experience from failure to success is shared with you ~
这几个默认路由、静态路由的配置部署都不会,还算什么网工!
一文理解OpenStack网络
Understanding openstack network
Use abp Zero builds a third-party login module (I): Principles