热门角色不仅是灵感来源,更是你的效率助手。通过精挑细选的角色提示词,你可以快速生成高质量内容、提升创作灵感,并找到最契合你需求的解决方案。让创作更轻松,让价值更直接!
我们根据不同用户需求,持续更新角色库,让你总能找到合适的灵感入口。
本提示词专为JavaScript开发者设计,能够根据用户提供的数组名称和具体需求,生成符合最佳实践的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(与需求一致)
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 }
/**
* 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));
}
// 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));
使用时的注意事项和常见问题
性能优化建议
兼容性说明
/**
* 将嵌套购物车 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)
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));
将“我需要对某个数组做X处理”的一句话需求,快速转换为可直接落地的高质量 reduce 函数方案。覆盖求和、统计、分组、去重、对象合并、嵌套数据展开等高频场景,自动生成完整函数实现、清晰注释、调用示例与使用注意事项,帮助个人与团队在数分钟内完成从需求→代码→校验的闭环,显著提升开发效率、减少缺陷、统一代码风格并降低沟通与维护成本。
在迭代中快速产出订单汇总、分类计数、列表去重等聚合逻辑的reduce函数,直接复制可用,缩短开发与评审时间。
为日志聚合、访问统计、数据转换流水线快速生成稳健实现,自动处理初始值与边界情况,减少线上风险。
将原始数组快速加工为报表所需维度与指标,一键生成分组、分桶与汇总逻辑,缩短图表落地周期。
将模板生成的提示词复制粘贴到您常用的 Chat 应用(如 ChatGPT、Claude 等),即可直接对话使用,无需额外开发。适合个人快速体验和轻量使用场景。
把提示词模板转化为 API,您的程序可任意修改模板参数,通过接口直接调用,轻松实现自动化与批量处理。适合开发者集成与业务系统嵌入。
在 MCP client 中配置对应的 server 地址,让您的 AI 应用自动调用提示词模板。适合高级用户和团队协作,让提示词在不同 AI 工具间无缝衔接。
半价获取高级提示词-优惠即将到期