当前位置:网站首页>10 个 Reduce 常用“奇技淫巧”
10 个 Reduce 常用“奇技淫巧”
2022-07-26 11:11:00 【InfoQ】
累加/累积
// adder
const sum = (...nums) => {
return nums.reduce((sum, num) => sum + num);
};
console.log(sum(1, 2, 3, 4, 10)); // 20
// accumulator
const accumulator = (...nums) => {
return nums.reduce((acc, num) => acc * num);
};
console.log(accumulator(1, 2, 3)); // 6
求最大/最小值
const array = [-1, 10, 6, 5];
const max = Math.max(...array); // 10
const min = Math.min(...array); // -1
const array = [-1, 10, 6, 5];
const max = array.reduce((max, num) => (max > num ? max : num));
const min = array.reduce((min, num) => (min < num ? min : num));
格式化搜索参数
// url https://qianlongo.github.io/vue-demos/dist/index.html?name=fatfish&age=100#/home
// format the search parameters
{
"name": "fatfish",
"age": "100"
}
const parseQuery = () => {
const search = window.location.search;
let query = {};
search
.slice(1)
.split("&")
.forEach((it) => {
const [key, value] = it.split("=");
query[key] = decodeURIComponent(value);
});
return query;
};
const parseQuery = () => {
const search = window.location.search;
return search
.slice(1)
.split("&")
.reduce((query, it) => {
const [key, value] = it.split("=");
query[key] = decodeURIComponent(value);
return query;
}, {});
};
反序列化搜索参数
const searchObj = {
name: "fatfish",
age: 100,
// ...
};
const link = `https://medium.com/?name=${searchObj.name}&age=${searchObj.age}`;
// https://medium.com/?name=fatfish&age=100
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
拉平嵌套数组
const array = [1, [2, [3, [4, [5]]]]];
// expected output [ 1, 2, 3, 4, 5 ]
const flatArray = array.flat(Infinity); // [1, 2, 3, 4, 5]
const flat = (array) => {
return array.reduce(
(acc, it) => acc.concat(Array.isArray(it) ? flat(it) : it),
[]
);
};
const array = [1, [2, [3, [4, [5]]]]];
const flatArray = flat(array); // [1, 2, 3, 4, 5]
实现 flat
// 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))
数组去重
const array = [ 1, 2, 1, 2, -1, 10, 11 ]
const uniqueArray1 = [ ...new Set(array) ]
const uniqueArray2 = array.reduce((acc, it) =>
acc.includes(it)
? acc
: [ ...acc, it ], [])
数组计数
const count = (array) => {
return array.reduce((acc, it) => (acc.set(it, (acc.get(it) || 0) + 1), acc), new Map())
}
const array = [ 1, 2, 1, 2, -1, 0, '0', 10, '10' ]
console.log(count(array)) // Map(7) {1 => 2, 2 => 2, -1 => 1, 0 => 1, '0' => 1, …}
获取对象多个属性
// 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?
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)
反转字符串
const reverseString = (string) => {
return string.split("").reduceRight((acc, s) => acc + s)
}
const string = 'fatfish'
console.log(reverseString(string)) // hsiftaf
边栏推荐
- Connection between PLC and servo motor
- Three properties of concurrency
- mysql数据库进阶
- 正点原子stm32中hal库iic模拟`#define SDA_IN() {GPIOB->MODER&=~(3<<(9*2));GPIOB->MODER|=0<<9*2;}` //PB9 输入模式
- Smart contract DAPP system development process technology
- Creation and modification of basic tables and data in them by SQL statements of SQL Server
- Want the clouds in the picture to float? Video editing services can be achieved in three steps with one click
- 打造绿色数据中心,Colt DCS 是认真的!
- JVM基本概念及内存管理模型
- Pyechart离线部署
猜你喜欢

QT——LCDNumber

Leetcode-209. subarray with the smallest length (binary, prefix and, sliding window)

Pyqt5 rapid development and practice Chapter 1 understanding pyqt5

LinkedList of source code

梅科尔工作室-华为14天鸿蒙设备开发实战笔记八

easyui05

Scrapy shell出现的一个错误

Caused by: scala. MatchError: None (of class scala.None$)
![[vscode] how to connect to the server remotely](/img/b4/9a80ad995bd589596d8b064215b55a.png)
[vscode] how to connect to the server remotely

加载ORB词典
随机推荐
In depth interpretation of happens before principle
SQL statement of SQL server creates database
MySQL事务详解
What does it mean that the configuration file ends in RC
李宏毅《机器学习》丨2. Regression(回归)
Static routing and dynamic routing
程序员成长第二十八篇:管理者如何才能不亲力亲为?
Want the clouds in the picture to float? Video editing services can be achieved in three steps with one click
Access rights - private, public, protected
Build neural network from simple to deep
Pyechart离线部署
《微信小程序-进阶篇》Lin-ui组件库源码分析-Button组件(一)
QT——LCDNumber
Caused by: scala. MatchError: None (of class scala.None$)
leetcode-209. 长度最小的子数组(二分、前缀和、滑动窗口)
Real time streaming protocol --rtsp
Dichotomous template summary
找工作4个月,面试15家,终于拿到3个offer,定级P7+
MySQL locking mechanism
MySQL数据库的简单使用