×
¥
查看详情
🔥 会员专享 文生文 代码生成

JavaScript数组归约函数生成器

👁️ 72 次查看
📅 Dec 8, 2025
💡 核心价值: 本提示词专为JavaScript开发者设计,能够根据用户提供的数组名称和具体需求,生成符合最佳实践的reduce函数代码。通过系统化的分析流程,确保输出的代码具备技术准确性、逻辑清晰性和实用性,涵盖常见的数据处理场景如求和、统计、分组等,帮助开发者快速实现数组元素的累积计算功能,提升开发效率。

🎯 可自定义参数(3个)

数组名称
需要进行reduce操作的数组名称
数据处理需求
通过reduce函数实现的具体数据处理需求
输出语言
输出内容的语言偏好

🎨 效果示例

Reduce函数实现

函数代码

/**
 * 使用 Array.prototype.reduce 统计已支付订单的总金额与数量
 * - 仅统计 status === 'paid' 的订单
 * - 忽略 status 为 'cancelled' 或其他状态的订单
 * - 忽略无效金额(非数字 / NaN / Infinity)
 *
 * @param {Array<object>} orders - 订单数组(例如:userOrders)
 * 每个订单推荐包含以下字段:
 *   - status {string} 订单状态,示例:'paid' | 'cancelled' | ...
 *   - amount {number|string} 订单金额,支持数字或可转换为数字的字符串
 *
 * @returns {{ total: number, count: number }} 返回总金额与数量
 *   - total: 已支付订单金额求和(number)
 *   - count: 已支付订单数量(number)
 */
function summarizePaidOrders(orders) {
  // 输入校验:非数组或空数组直接返回零值结果,避免抛错并方便上层调用
  if (!Array.isArray(orders) || orders.length === 0) {
    return { total: 0, count: 0 };
  }

  // 使用 reduce 进行聚合
  const result = orders.reduce(
    (acc, order) => {
      // 跳过非对象或空值
      if (order == null || typeof order !== 'object') return acc;

      // 仅统计已支付订单
      if (order.status !== 'paid') return acc;

      // 金额转换与校验:允许字符串形式的数值(例如 "30.5")
      const raw = typeof order.amount === 'string' ? order.amount.trim() : order.amount;
      const amount = Number(raw);

      // 忽略无效金额(NaN、Infinity、-Infinity 或非数字)
      if (!Number.isFinite(amount)) return acc;

      acc.total += amount;
      acc.count += 1;
      return acc;
    },
    { total: 0, count: 0 } // 初始累积值
  );

  return result;
}

代码说明

  • 函数功能:对给定的订单数组(如 userOrders)进行归约聚合,仅统计 status 为 'paid' 的订单,计算其总金额与数量,返回 { total, count }。
  • 参数说明:
    • orders:Array,订单数组。每个订单建议至少包含:
      • status:string,订单状态(仅当为 'paid' 时统计)
      • amount:number|string,订单金额,支持可被 Number() 正确转换的字符串
    • 返回值:
      • { total: number, count: number }
        • total:所有已支付订单的金额之和
        • count:已支付订单的数量
    • 使用示例

      // 示例数据:数组名称为 userOrders(与需求一致)
      const userOrders = [
        { id: 1, status: 'paid', amount: 19.5 },
        { id: 2, status: 'cancelled', amount: 5 },
        { id: 3, status: 'paid', amount: '30.5' }, // 支持字符串金额
        { id: 4, status: 'paid', amount: null },   // 无效金额将被忽略
        { id: 5, status: 'refunded', amount: 10 }, // 非 'paid' 状态不计入
      ];
      
      const summary = summarizePaidOrders(userOrders);
      console.log(summary); 
      // 预期输出:{ total: 50, count: 2 }
      

      注意事项

      • 数据完整性:
        • 如果订单对象缺少 status 或 amount 字段,该订单将被忽略或不计入总金额。
        • 无法转换为有限数值(如 NaN、Infinity、空字符串、null)的 amount 会被忽略,不会影响 count。
      • 金额精度:
        • JavaScript 使用二进制浮点,可能出现小数精度问题(例如 0.1 + 0.2 !== 0.3)。
        • 若对金额精度要求严格,建议:
          • 将金额转为最小货币单位(如分)以整数累加:例如 Math.round(amount * 100) 后再除以 100 输出;
          • 或使用专门的十进制库(如 decimal.js、big.js)。
      • 性能优化建议:
        • reduce 为 O(n) 单次遍历,已是本场景最优复杂度。
        • 如数据量超大且需多指标统计,考虑在一次 reduce 中同时汇总多个指标,避免多次遍历。
      • 兼容性说明:
        • 代码采用 ES6+ 语法(const、let、箭头函数、Number.isFinite),在现代浏览器与 Node.js 环境中均可运行。
        • 如需在非常旧的环境中运行,请使用 Babel 进行转译或替换箭头函数等语法。

      Reduce函数实现

      函数代码

      /**
       * Aggregate comment statistics by author using Array.prototype.reduce.
       *
       * Input:  articleComments: Array<{ author: string, likes?: number | string }>
       * Output: { [author: string]: { count: number, likes: number } }
       *
       * Rules:
       * - Each valid item counts as one comment for its author.
       * - likes are summed per author; non-numeric or missing likes are treated as 0.
       * - If author is missing/blank/non-string, it is grouped under "(unknown)".
       *
       * Complexity: O(n) time, O(k) space (k = number of unique authors).
       */
      function summarizeCommentsByAuthor(articleComments) {
        if (!Array.isArray(articleComments)) {
          throw new TypeError('summarizeCommentsByAuthor: expected articleComments to be an array');
        }
      
        // Helper: convert various inputs to a safe finite number; fallback to 0
        const toFiniteNumber = (value) => {
          if (typeof value === 'number') return Number.isFinite(value) ? value : 0;
          if (typeof value === 'string') {
            const n = Number(value.trim());
            return Number.isFinite(n) ? n : 0;
          }
          return 0;
        };
      
        // Use a null-prototype object to avoid inherited keys interfering with author names.
        return articleComments.reduce((acc, item, index) => {
          // Skip non-object items gracefully
          if (item == null || typeof item !== 'object') {
            // You may log/debug here if desired:
            // console.warn(`Skipping non-object at index ${index}`, item);
            return acc;
          }
      
          const rawAuthor = item.author;
          const author =
            typeof rawAuthor === 'string' && rawAuthor.trim().length > 0
              ? rawAuthor.trim()
              : '(unknown)';
      
          const likes = toFiniteNumber(item.likes);
      
          // Initialize bucket if not present
          if (!Object.prototype.hasOwnProperty.call(acc, author)) {
            acc[author] = { count: 0, likes: 0 };
          }
      
          // Accumulate
          acc[author].count += 1;
          acc[author].likes += likes;
      
          return acc;
        }, Object.create(null));
      }
      

      代码说明

      • 函数功能:
        • Traverse the articleComments array once and build an object where each key is an author and each value contains:
          • count: number of comments by that author
          • likes: total likes summed across that author’s comments
      • 参数说明:
        • articleComments: Array
          • Each element is expected to be an object with:
            • author: string (required to group; if missing/invalid, grouped as "(unknown)")
            • likes: number|string (optional; non-numeric or missing values are treated as 0)
      • 返回值:
        • Object mapping author => { count: number, likes: number }
        • Uses a null-prototype object to safeguard against prototype key collisions, while remaining JSON-serializable.

      使用示例

      // Example input array (articleComments)
      const articleComments = [
        { author: 'Alice', likes: 5 },
        { author: 'Bob', likes: '3' },
        { author: 'Alice', likes: 2 },
        { author: 'Charlie', likes: 10 },
        { author: 'Bob', likes: null },     // treated as 0
        { author: '', likes: 4 },           // blank author -> "(unknown)"
        { author: 'Alice', likes: 'NaN' },  // non-numeric string -> 0
        { likes: 7 },                       // missing author -> "(unknown)"
        'not-an-object',                    // skipped
        { author: 'Bob', likes: Infinity }, // non-finite -> 0
      ];
      
      const summary = summarizeCommentsByAuthor(articleComments);
      
      console.log(summary);
      // Expected output (order of keys may vary):
      // {
      //   Alice:   { count: 3, likes: 7 },   // 5 + 2 + 0
      //   Bob:     { count: 3, likes: 3 },   // 3 + 0 + 0
      //   Charlie: { count: 1, likes: 10 },
      //   "(unknown)": { count: 2, likes: 11 } // 4 + 7
      // }
      
      // If you need to serialize:
      console.log(JSON.stringify(summary, null, 2));
      

      注意事项

      • 使用时的注意事项和常见问题

        • Validation: The function throws a TypeError if the input is not an array.
        • Unknown authors: Missing/blank/non-string author values are grouped under "(unknown)". Adjust as needed (e.g., throw or skip).
        • Non-object items are skipped safely.
        • likes normalization: Non-finite values (NaN, Infinity) and non-numeric strings become 0.
        • Output order: Object key order is not guaranteed. If you need sorted results, sort keys after reduction.
      • 性能优化建议

        • The function runs in O(n) time with a single pass reduce.
        • For very large datasets, minimize intermediate allocations and logging inside the reducer.
        • If you need to frequently merge partial summaries, consider using Maps during intermediate steps and convert to plain objects at the end.
      • 兼容性说明

        • Uses ES6+ features (const/let, arrow functions, Object.prototype.hasOwnProperty.call).
        • Works in modern browsers and Node.js (v12+). If targeting older environments, transpile accordingly.

      Reduce函数实现

      函数代码

      /**
       * 将嵌套购物车 items 展平,并按 sku 去重:
       * - quantity 累加
       * - price 保留“最新”值(可选:按遍历顺序的最后出现或按时间戳)
       *
       * 设计要点:
       * 1) 使用单一 Map 作为累加容器,键为 sku(字符串化以避免 '1' 与 1 的混淆)
       * 2) 使用 reduce 实现遍历与累积,同时递归处理任意层级的嵌套数组
       * 3) 提供两种“最新 price”策略:lastSeen(默认)与 byTimestamp
       *
       * @param {Array} cartItemsNested - 可能包含任意层级嵌套数组的购物车条目
       *   每个条目建议形如:{ sku: string|number, quantity: number|string, price: number|string, updatedAt?: string|Date }
       * @param {Object} [options]
       * @param {'lastSeen'|'byTimestamp'} [options.selectPrice='lastSeen']
       *   - 'lastSeen': 以遍历顺序中“最后一次出现”的 price 为准
       *   - 'byTimestamp': 以时间戳更近(更大)的条目决定 price
       * @param {(item:any)=>number|string|Date} [options.getTimestamp]
       *   - 自定义从条目读取时间戳的方法。缺省时尝试读取 item.updatedAt
       * @returns {Array<{ sku: string, quantity: number, price: number|undefined }>}
       */
      function mergeCartBySkuReduce(cartItemsNested, options = {}) {
        if (!Array.isArray(cartItemsNested)) {
          throw new TypeError('cartItemsNested 必须是数组');
        }
      
        const { selectPrice = 'lastSeen', getTimestamp } = options;
      
        // 计算时间戳(毫秒)。返回 NaN 表示无效时间戳。
        const computeTs = (item) => {
          if (typeof getTimestamp === 'function') {
            const v = getTimestamp(item);
            if (v instanceof Date) return v.getTime();
            const n = Number(v);
            if (Number.isFinite(n)) return n;
            const parsed = Date.parse(v);
            return Number.isFinite(parsed) ? parsed : NaN;
          }
          if (item && 'updatedAt' in item) {
            const v = item.updatedAt;
            const n = v instanceof Date ? v.getTime() : Date.parse(v);
            return Number.isFinite(n) ? n : NaN;
          }
          return NaN;
        };
      
        // 可靠的数值转换(无法转换时使用 fallback)
        const toNumber = (x, fallback = 0) => {
          const n = Number(x);
          return Number.isFinite(n) ? n : fallback;
        };
      
        // 将节点累积进 Map(递归处理数组)
        const aggregate = (accMap, node) => {
          if (node == null) return accMap;
      
          if (Array.isArray(node)) {
            // 用 reduce 递归地遍历子数组(保持纯 reduce 风格)
            node.reduce((map, child) => {
              aggregate(map, child);
              return map;
            }, accMap);
            return accMap;
          }
      
          // 处理叶子条目
          const skuKey = String(node.sku ?? '').trim();
          if (!skuKey) return accMap; // 跳过无效 sku
      
          const qty = toNumber(node.quantity, 0);
          const priceNum = Number.isFinite(Number(node.price)) ? Number(node.price) : undefined;
      
          const exist = accMap.get(skuKey);
      
          if (!exist) {
            accMap.set(skuKey, {
              sku: skuKey,
              quantity: qty,
              price: priceNum,
              __ts: computeTs(node), // 内部时间戳,仅用于比较
            });
            return accMap;
          }
      
          // 累计数量
          exist.quantity += qty;
      
          // 更新价格策略
          if (selectPrice === 'byTimestamp') {
            const curTs = computeTs(node);
            const curValid = Number.isFinite(curTs);
            const prevValid = Number.isFinite(exist.__ts);
      
            if (curValid && (!prevValid || curTs >= exist.__ts)) {
              if (priceNum !== undefined) exist.price = priceNum;
              exist.__ts = curTs;
            } else if (!curValid && !prevValid) {
              // 两者都没有有效时间戳时,退化为“最后出现优先”
              if (priceNum !== undefined) exist.price = priceNum;
            }
          } else {
            // 默认:遍历中的最后一次出现覆盖之前的 price
            if (priceNum !== undefined) exist.price = priceNum;
          }
      
          return accMap;
        };
      
        // 主 reduce:从顶层开始累积
        const map = cartItemsNested.reduce((acc, node) => {
          aggregate(acc, node);
          return acc;
        }, new Map());
      
        // 输出数组,去掉内部字段 __ts
        return Array.from(map.values()).map(({ __ts, ...rest }) => rest);
      }
      

      代码说明

      • 函数功能:
        • 展平任意层级的嵌套购物车数组 cartItemsNested
        • 按 sku 去重并对 quantity 求和
        • price 保留“最新”值,支持两种策略:
          • lastSeen(默认):以遍历顺序中最后一次出现的 price 为准
          • byTimestamp:以时间戳(updatedAt 或自定义 getTimestamp)较新的条目为准
      • 参数说明:
        • cartItemsNested:数组(可嵌套),元素可为对象或子数组。对象建议包含 sku、quantity、price,亦可包含 updatedAt
        • options.selectPrice:'lastSeen' 或 'byTimestamp'
        • options.getTimestamp:可选函数,用于从条目中提取比较时间戳,返回 number/string/Date,未提供时默认读取 item.updatedAt
      • 返回值:
        • 去重合并后的数组,元素结构:
          • { sku: string, quantity: number, price: number|undefined }

      使用示例

      // 示例数据(名称按题意:cartItemsNested)
      const cartItemsNested = [
        [
          { sku: 'A1', quantity: 1, price: 10, updatedAt: '2024-01-01T10:00:00Z' },
          [
            { sku: 'B2', quantity: 2, price: 20, updatedAt: '2024-01-02T10:00:00Z' },
            { sku: 'A1', quantity: 2, price: 11, updatedAt: '2024-01-15T10:00:00Z' },
          ],
        ],
        { sku: 'B2', quantity: 1, price: 18, updatedAt: '2023-12-31T10:00:00Z' },
        null, // 将被忽略
        [{ sku: 'C3', quantity: '3', price: '30.5' }], // 字符串也会被安全转换
      ];
      
      // 1) 默认策略:lastSeen(以最后一次出现为准)
      const mergedLastSeen = mergeCartBySkuReduce(cartItemsNested);
      /*
      期望输出:
      [
        { sku: 'A1', quantity: 3, price: 11 },   // A1: 1+2=3,最后一次 price=11
        { sku: 'B2', quantity: 3, price: 18 },   // B2: 2+1=3,最后一次 price=18
        { sku: 'C3', quantity: 3, price: 30.5 }  // C3: 3,price 30.5
      ]
      */
      console.log('lastSeen =>', JSON.stringify(mergedLastSeen));
      
      // 2) 时间戳策略:byTimestamp(以时间较新的条目为准)
      const mergedByTs = mergeCartBySkuReduce(cartItemsNested, { selectPrice: 'byTimestamp' });
      /*
      期望输出:
      [
        { sku: 'A1', quantity: 3, price: 11 },   // A1: 时间较新的是 2024-01-15 => price=11
        { sku: 'B2', quantity: 3, price: 20 },   // B2: 时间较新的是 2024-01-02 => price=20
        { sku: 'C3', quantity: 3, price: 30.5 }
      ]
      */
      console.log('byTimestamp =>', JSON.stringify(mergedByTs));
      
      // 3) 自定义时间戳字段(例如 updated_at_ms 是毫秒时间戳)
      const cartWithCustomTs = [
        { sku: 'X1', quantity: 1, price: 99, updated_at_ms: 1712120000000 },
        { sku: 'X1', quantity: 2, price: 120, updated_at_ms: 1712200000000 },
      ];
      const mergedCustom = mergeCartBySkuReduce(cartWithCustomTs, {
        selectPrice: 'byTimestamp',
        getTimestamp: (item) => item.updated_at_ms,
      });
      /*
      [
        { sku: 'X1', quantity: 3, price: 120 }
      ]
      */
      console.log('custom ts =>', JSON.stringify(mergedCustom));
      

      注意事项

      • 数据有效性:
        • 无效项(null/undefined)、无 sku 的条目会被跳过
        • quantity/price 会尝试用 Number(...) 转换;无法转换时 quantity 记为 0,price 记为 undefined(不覆盖已有价格)
      • “最新价格”策略说明:
        • lastSeen:价格由遍历顺序决定(本实现为深度优先、从左到右),更靠后的条目覆盖更前的条目
        • byTimestamp:若条目存在有效时间戳,取时间更近者;若双方都无有效时间戳,则退化为 lastSeen
      • sku 归一化:
        • 以 String(item.sku).trim() 作为去重键。可避免 1 与 '1' 混淆但会将不同类型合并为同一 SKU,如需严格区分可改为不字符串化
      • 性能建议:
        • 时间复杂度 O(N),空间复杂度 O(U)(U 为去重后 SKU 数量)
        • Map 作为累加容器在大量键值场景下更高效
        • 极深的嵌套层级(> 数千层)可能导致递归过深,可改为显式栈迭代处理
      • 兼容性:
        • 依赖 ES6+ 特性(Map、箭头函数、解构等),可在现代浏览器与 Node.js 12+ 正常运行
        • 旧环境请使用相应 polyfill 或将语法降级处理

      示例详情

      📖 如何使用

      30秒出活:复制 → 粘贴 → 搞定
      与其花几十分钟和AI聊天、试错,不如直接复制这些经过千人验证的模板,修改几个 {{变量}} 就能立刻获得专业级输出。省下来的时间,足够你轻松享受两杯咖啡!
      加载中...
      💬 不会填参数?让 AI 反过来问你
      不确定变量该填什么?一键转为对话模式,AI 会像资深顾问一样逐步引导你,问几个问题就能自动生成完美匹配你需求的定制结果。零门槛,开口就行。
      转为对话模式
      🚀 告别复制粘贴,Chat 里直接调用
      无需切换,输入 / 唤醒 8000+ 专家级提示词。 插件将全站提示词库深度集成于 Chat 输入框。基于当前对话语境,系统智能推荐最契合的 Prompt 并自动完成参数化,让海量资源触手可及,从此彻底告别"手动搬运"。
      即将推出
      🔌 接口一调,提示词自己会进化
      手动跑一次还行,跑一百次呢?通过 API 接口动态注入变量,接入批量评价引擎,让程序自动迭代出更高质量的提示词方案。Prompt 会自己进化,你只管收结果。
      发布 API
      🤖 一键变成你的专属 Agent 应用
      不想每次都配参数?把这条提示词直接发布成独立 Agent,内嵌图片生成、参数优化等工具,分享链接就能用。给团队或客户一个"开箱即用"的完整方案。
      创建 Agent

      ✅ 特性总结

      基于你的数组与需求,一键生成可读性强的reduce实现与调用示例
      内置求和、计数、分组、去重等常用场景模板,开箱即用快速落地
      自动补齐初始值与累积逻辑,规避空数组、异常数据等边界风险
      生成代码附详细注释与说明,便于团队协作与快速二次改造
      按现代语法与规范输出,兼顾性能与可维护性,减少后期返工
      可按业务字段定制聚合规则,灵活适配电商、数据分析等场景
      提供可复制的运行示例与预期结果,降低调试成本立即验证
      内置质量自检步骤,自动优化变量命名与结构,让代码更清爽
      支持中文输出说明,便于文档化与交付,提高团队学习效率

      🎯 解决的问题

      将“我需要对某个数组做X处理”的一句话需求,快速转换为可直接落地的高质量 reduce 函数方案。覆盖求和、统计、分组、去重、对象合并、嵌套数据展开等高频场景,自动生成完整函数实现、清晰注释、调用示例与使用注意事项,帮助个人与团队在数分钟内完成从需求→代码→校验的闭环,显著提升开发效率、减少缺陷、统一代码风格并降低沟通与维护成本。

      🕒 版本历史

      当前版本
      v2.1 2024-01-15
      优化输出结构,增强情节连贯性
      • ✨ 新增章节节奏控制参数
      • 🔧 优化人物关系描述逻辑
      • 📝 改进主题深化引导语
      • 🎯 增强情节转折点设计
      v2.0 2023-12-20
      重构提示词架构,提升生成质量
      • 🚀 全新的提示词结构设计
      • 📊 增加输出格式化选项
      • 💡 优化角色塑造引导
      v1.5 2023-11-10
      修复已知问题,提升稳定性
      • 🐛 修复长文本处理bug
      • ⚡ 提升响应速度
      v1.0 2023-10-01
      首次发布
      • 🎉 初始版本上线
      COMING SOON
      版本历史追踪,即将启航
      记录每一次提示词的进化与升级,敬请期待。

      💬 用户评价

      4.8
      ⭐⭐⭐⭐⭐
      基于 28 条评价
      5星
      85%
      4星
      12%
      3星
      3%
      👤
      电商运营 - 张先生
      ⭐⭐⭐⭐⭐ 2025-01-15
      双十一用这个提示词生成了20多张海报,效果非常好!点击率提升了35%,节省了大量设计时间。参数调整很灵活,能快速适配不同节日。
      效果好 节省时间
      👤
      品牌设计师 - 李女士
      ⭐⭐⭐⭐⭐ 2025-01-10
      作为设计师,这个提示词帮我快速生成创意方向,大大提升了工作效率。生成的海报氛围感很强,稍作调整就能直接使用。
      创意好 专业
      COMING SOON
      用户评价与反馈系统,即将上线
      倾听真实反馈,在这里留下您的使用心得,敬请期待。
      加载中...