本文深入解析JavaScript中Array.prototype.reduce方法的10个常用场景与技巧。内容涵盖累加累积、极值计算、URL参数解析与序列化、嵌套数组扁平化、数组去重与计数、对象属性提取及字符串反转等实用案例,帮助开发者更高效地利用Reduce实现复杂逻辑。
许多开发者可能较少使用 Reduce 方法,但实际上它的应用范围远超想象。本文将介绍10个Reduce的常见应用场景和技巧,其中或许包含你未曾了解的使用方法。
让我们开始探索吧!
累加/累积
累加可能是大家最熟悉的Reduce用法,此外,它还可以用于累积计算。
// 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
求最大/最小值
虽然使用原生API求最大/最小值无可厚非,但Reduce同样可以实现相同的效果。
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上的参数是常见需求,使用forEach遍历可行,而用Reduce累加则更为简洁,能减少声明query对象的步骤。
// 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;
}, {});
};
反序列化搜索参数
既然有获取URL参数的方法,自然也有将参数重新挂载到URL上的需求,实用且值得收藏。
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
拉平嵌套数组
我们通常使用.flat(Infinity)将多维数组无限拉平为一维数组,而仅用reduce和flat也能实现这一功能。
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
若想手动实现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))
数组去重
使用Reduce进行数组去重也是可行的,具体写法如下:
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 ], [])
数组计数
对数组项进行计数并返回包含每项重复次数的Map,使用Reduce一行代码即可搞定,值得收藏。
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?
使用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)
反转字符串
除了使用reverse翻转数组,Reduce结合split也能实现字符串的反转。
const reverseString = (string) => {
return string.split("").reduceRight((acc, s) => acc + s)
}
const string = 'fatfish'
console.log(reverseString(string)) // hsiftaf以上就是JavaScript中Reduce10个常用场景和技巧的详细内容,更多关于JavaScript Reduce技巧的资料请关注本站其它相关文章!