当前位置:网站首页>10 reduce common "tricks"
10 reduce common "tricks"
2022-07-26 11:41:00 【InfoQ】
Add up / The cumulative
// 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
Ask for the biggest / minimum value
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));
Format search parameters
// 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;
}, {});
};
Deserialize search parameters
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
Flatten nested arrays
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]
Realization 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))
Array weight removal
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 ], [])
Array count
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, …}
Get multiple properties of the object
// 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)
Reverse string
const reverseString = (string) => {
return string.split("").reduceRight((acc, s) => acc + s)
}
const string = 'fatfish'
console.log(reverseString(string)) // hsiftaf
边栏推荐
- 3.2 创建菜单与游戏页面(下)
- Build neural network from simple to deep
- The company cannot access station B
- 【云驻共创】为了写好代码,你坚持了哪些好习惯?
- Outsourcing for four years, abandoned
- 如何使用数据管道实现测试现代化
- Scrapy IP agent is not responding
- Application scheme of ankerui residual pressure monitoring system in residential quarter
- Understanding of Abstract Programming
- MySQL transaction details
猜你喜欢

QT——LCDNumber

Pyechart offline deployment

Cmake常用命令总结

元宇宙GameFi链游系统开发NFT技术

MySQL transaction details

Practice of microservice in solving Library Download business problems

A new technical director asked me to do an IP territorial function~

MySQL deadlock analysis

微服务化解决文库下载业务问题实践

After 4 months of job search and 15 interviews, I finally got 3 offers, ranking P7+
随机推荐
。。。。。。
Generation and transformation of pulse waveform
Rigorous proof of Behrman's expectation equation
Machine learning by Li Hongyi 2. Regression
正点原子stm32中hal库iic模拟`#define SDA_IN() {GPIOB->MODER&=~(3<<(9*2));GPIOB->MODER|=0<<9*2;}` //PB9 输入模式
Three properties of concurrency
LeetCode / Scala - 两数,三数,四数,N数之和
Mysql database advanced
记录个人遇到的错误
[vscode]如何远程连接服务器
Understanding of Abstract Programming
MongoDN数据库以URL形式连接
A new technical director asked me to do an IP territorial function~
Exploration on cache design optimization of community like business
Query advanced alias
程序员成长第二十八篇:管理者如何才能不亲力亲为?
MySQL transaction details
702马力破百仅4.5秒!最强皮卡来袭,安全、舒适一个不落
服务器内存故障预测居然可以这样做!
Summary of common cmake commands