• 10个Reduce函数的使用小技巧


    作为一个前端开发者,你一定会大量使用reduce函数,它是一个强大而有用的数组api,但是,今天我想给大家分享10个关于它的进阶技巧。

    1、作为加法器和累加器

    使用“reduce”,我们可以轻松实现多个数相加或累加的功能。

    1. // adder
    2. const sum = (...nums) => {
    3. return nums.reduce((sum, num) => sum + num);
    4. };
    5. console.log(sum(1, 2, 3, 4, 10)); // 20
    6. // accumulator
    7. const accumulator = (...nums) => {
    8. return nums.reduce((acc, num) => acc * num);
    9. };
    10. console.log(accumulator(1, 2, 3)); // 6

    2、计算一个数组的最大值和最小值

    有多少种方法可以得到数组的最大值或最小值?

    1):使用 Math.max 和 Math.min

    我们不得不承认,使用 Math 的 API 是最简单的方法。

    1. const array = [-1, 10, 6, 5];
    2. const max = Math.max(...array); // 10
    3. const min = Math.min(...array); // -1

    2):使用减少

    是的,只需一行代码,我们就可以实现与 Math 的 API 相同的效果。

    1. const array = [-1, 10, 6, 5];
    2. const max = array.reduce((max, num) => (max > num ? max : num));
    3. const min = array.reduce((min, num) => (min < num ? min : num));

    3、格式化搜索参数

    获取链接上的搜索参数是我们经常要处理的事情。如何解析它们?

    例如:

    1. // url https://qianlongo.github.io/vue-demos/dist/index.html?name=fatfish&age=100#/home
    2. // format the search parameters
    3. {
    4. "name": "fatfish",
    5. "age": "100"
    6. }

    1)、正常方式

    这是大多数人使用它的方式。

    1. const parseQuery = () => {
    2. const search = window.location.search;
    3. let query = {};
    4. search
    5. .slice(1)
    6. .split("&")
    7. .forEach((it) => {
    8. const [key, value] = it.split("=");
    9. query[key] = decodeURIComponent(value);
    10. });
    11. return query;
    12. };

    2)、使用reduce

    Reduce 实际上可以做到这一点,而且看起来更简单。

    1. const parseQuery = () => {
    2. const search = window.location.search;
    3. return search
    4. .replace(/(^\?)|(&$)/g, "")
    5. .split("&")
    6. .reduce((query, it) => {
    7. const [key, value] = it.split("=");
    8. query[key] = decodeURIComponent(value);
    9. return query;
    10. }, {});
    11. };

    它是如何工作的?

    1. / url https://qianlongo.github.io/vue-demos/dist/index.html?name=fatfish&age=100#/home
    2. // 1. First get the search parameter
    3. const search = window.location.search; // ?name=fatfish&age=100
    4. // 2. Remove the beginning "?" or ending "&".
    5. search.replace(/(^\?)|(&$)/g, "");
    6. // ?name=fatfish&age=100 => name=fatfish&age=100
    7. // 3. Use reduce to collect parameters
    8. // ...

    4、反序列化搜索参数

    当我们要跳转到某个链接并为其添加一些搜索参数时,手动拼接的方式不是很方便。

    如果要串联的参数很多,那将是一场灾难。

    1. const searchObj = {
    2. name: "fatfish",
    3. age: 100,
    4. // ...
    5. };
    6. const link = `https://medium.com/?name=${searchObj.name}&age=${searchObj.age}`;
    7. // https://medium.com/?name=fatfish&age=100

    幸运的是,“reduce”可以帮助我们轻松解决这个问题。

    1. const stringifySearch = (search = {}) => {
    2. return Object.entries(search)
    3. .reduce(
    4. (t, v) => `${t}${v[0]}=${encodeURIComponent(v[1])}&`,
    5. Object.keys(search).length ? "?" : ""
    6. )
    7. .replace(/&$/, "");
    8. };
    9. const search = stringifySearch({
    10. name: "fatfish",
    11. age: 100,
    12. });
    13. const link = `https://medium.com/${search}`;
    14. console.log(link); // https://medium.com/?name=fatfish&age=100

    5、展平多层嵌套数组

    你知道如何展平多层嵌套数组吗?

    1. const array = [1, [2, [3, [4, [5]]]]];
    2. // expected output [ 1, 2, 3, 4, 5 ]
    3. const flatArray = array.flat(Infinity); // [1, 2, 3, 4, 5]

    “flat”是一个非常强大的API。

    使用reduce实现和flat一样的功能。

    1. const flat = (array) => {
    2. return array.reduce(
    3. (acc, it) => acc.concat(Array.isArray(it) ? flat(it) : it),
    4. []
    5. );
    6. };
    7. const array = [1, [2, [3, [4, [5]]]]];
    8. const flatArray = flat(array); // [1, 2, 3, 4, 5]

    6、模拟平面特征的功能

    虽然我们已经实现了扁平化深度嵌套数组的功能,但是如何才能完全实现扁平化的功能呢?

    1. // Expand one layer by default
    2. Array.prototype.flat2 = function (n = 1) {
    3. const len = this.length
    4. let count = 0
    5. let current = this
    6. if (!len || n === 0) {
    7. return current
    8. }
    9. // Confirm whether there are array items in current
    10. const hasArray = () => current.some((it) => Array.isArray(it))
    11. // Expand one layer after each cycle
    12. while (count++ < n && hasArray()) {
    13. current = current.reduce((result, it) => {
    14. result = result.concat(it)
    15. return result
    16. }, [])
    17. }
    18. return current
    19. }
    20. const array = [ 1, [ 2, [ 3, [ 4, [ 5 ] ] ] ] ]
    21. // Expand one layer
    22. console.log(array.flat()) // [ 1, 2, [ 3, [ 4, [ 5 ] ] ] ]
    23. console.log(array.flat2()) // [ 1, 2, [ 3, [ 4, [ 5 ] ] ] ]
    24. // Expand all
    25. console.log(array.flat(Infinity))
    26. console.log(array.flat2(Infinity))

    7、保持数组唯一

    reduce 也很容易保持数组的唯一性。

    1. const array = [ 1, 2, 1, 2, -1, 10, 11 ]
    2. const uniqueArray1 = [ ...new Set(array) ]
    3. const uniqueArray2 = array.reduce((acc, it) => acc.includes(it) ? acc : [ ...acc, it ], [])

    8、统计数组成员的个数

    如何计算数组中每个成员的个数?

    为什么使用地图而不是对象?

    1. const count = (array) => {
    2. return array.reduce((acc, it) => (acc.set(it, (acc.get(it) || 0) + 1), acc), new Map())
    3. }
    4. const array = [ 1, 2, 1, 2, -1, 0, '0', 10, '10' ]
    5. console.log(count(array))

    9、获取一个对象的多个属性

    朋友们,让我们来看看你在工作中会遇到的一个场景。

    1. // There is an object with many properties
    2. const obj = {
    3. a: 1,
    4. b: 2,
    5. c: 3,
    6. d: 4,
    7. e: 5
    8. // ...
    9. }
    10. // We just want to get some properties above it to create a new object
    11. const newObj = {
    12. a: obj.a,
    13. b: obj.b,
    14. c: obj.c,
    15. d: obj.d
    16. // ...
    17. }
    18. // Do you think this is too inefficient?

    使用reduce来解决它

    1. const getObjectKeys = (obj = {}, keys = []) => {
    2. return Object.keys(obj).reduce((acc, key) => (keys.includes(key) && (acc[key] = obj[key]), acc), {});
    3. }
    4. const obj = {
    5. a: 1,
    6. b: 2,
    7. c: 3,
    8. d: 4,
    9. e: 5
    10. // ...
    11. }
    12. const newObj = getObjectKeys(obj, [ 'a', 'b', 'c', 'd' ])
    13. console.log(newObj)

    10、反转字符串

    1. const reverseString = (string) => {
    2. return string.split("").reduceRight((acc, s) => acc + s)
    3. }
    4. const string = 'fatfish'
    5. console.log(reverseString(string)) // hsiftaf
  • 相关阅读:
    分享图片或链接到抖音
    【抬杠C#】如何实现接口的base调用
    2022 极术通讯-安谋科技“星辰”STAR-MC2处理器初探
    uniapp在线打包ipa - iOS篇
    软件Bug和缺陷的区别是什么?
    VLAN实验一 VLAN的简单配置
    深度学习部署
    第十一周内容回顾
    Sprint framework Day07:注解结合 xml 配置
    Web前端大作业——城旅游景点介绍(HTML+CSS+JavaScript) html旅游网站设计与实现
  • 原文地址:https://blog.csdn.net/m0_64460287/article/details/127651127