You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中编辑JsonValue 提取合并≥45的数组元素实现方案咨询

数组筛选合并实现方案

核心思路是单次遍历拆分每个line数组的符合/不符合阈值的元素,分别收集后重组结果,相比嵌套for循环可读性更高,逻辑更易维护,时间复杂度和for循环一致为O(n)(n为所有数值的总个数)。

JavaScript实现示例

// 原始JSON数据
const originData = [{"line1":[1,3,5,7,9,11,13,15],"line2":[2,4,6,8,10,12,14,16]},{"line1":[17,19,21,23,25,27,29,31],"line2":[18,20,22,24,26,28,30,32]},{"line1":[33,35,37,39,41,43,45,47],"line2":[34,36,38,40,42,44,46,48]},{"line1":[49,51,53,55,57,59,61,63],"line2":[50,52,54,56,58,60,62,64]},{"line1":[65,67],"line2":[66,68]}];
const threshold = 45;

// 存储所有大于等于阈值的元素
const overThreshold = {
  line1: [],
  line2: []
};

const result = originData.map(item => {
  // 拆分line1的两组元素
  const [line1Under, line1Over] = item.line1.reduce((acc, num) => {
    num < threshold ? acc[0].push(num) : acc[1].push(num);
    return acc;
  }, [[], []]);
  // 拆分line2的两组元素
  const [line2Under, line2Over] = item.line2.reduce((acc, num) => {
    num < threshold ? acc[0].push(num) : acc[1].push(num);
    return acc;
  }, [[], []]);
  // 累计符合阈值的元素
  overThreshold.line1.push(...line1Over);
  overThreshold.line2.push(...line2Over);
  // 返回当前项中小于阈值的部分
  return { line1: line1Under, line2: line2Under };
// 过滤掉全空的项,最后追加累计的符合阈值的对象
}).filter(item => item.line1.length || item.line2.length).concat(overThreshold);

console.log(JSON.stringify(result));

Python实现示例

origin_data = [{"line1":[1,3,5,7,9,11,13,15],"line2":[2,4,6,8,10,12,14,16]},{"line1":[17,19,21,23,25,27,29,31],"line2":[18,20,22,24,26,28,30,32]},{"line1":[33,35,37,39,41,43,45,47],"line2":[34,36,38,40,42,44,46,48]},{"line1":[49,51,53,55,57,59,61,63],"line2":[50,52,54,56,58,60,62,64]},{"line1":[65,67],"line2":[66,68]}]
threshold = 45
over_threshold = {"line1": [], "line2": []}
result = []

for item in origin_data:
    line1_under = [x for x in item["line1"] if x < threshold]
    line1_over = [x for x in item["line1"] if x >= threshold]
    line2_under = [x for x in item["line2"] if x < threshold]
    line2_over = [x for x in item["line2"] if x >= threshold]
    over_threshold["line1"].extend(line1_over)
    over_threshold["line2"].extend(line2_over)
    if line1_under or line2_under:
        result.append({"line1": line1_under, "line2": line2_under})

result.append(over_threshold)
print(result)

方案优势

  • 无需手动维护多层循环的索引,避免下标写错的低级错误
  • 阈值可灵活调整,仅需修改threshold变量即可,改造成本低
  • 代码逻辑分层清晰,后续需要调整筛选规则时修改成本更低

内容的提问来源于stack exchange,提问作者Иван Афанасьев

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 21:36:08