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

如何合并两个等长、不同索引存非空值的含null数组

合并方案

核心逻辑为遍历两个数组的对应索引位,优先保留非null值即可,若同索引位两个数组都存在非null值,可自行调整取值优先级。

JavaScript 实现

// 取出对象中存储的两个数组
const [arr1, arr2] = obj;
const result = arr1.map((currentVal, index) => {
  // 空值合并运算符:当前值为null/undefined时,取第二个数组对应索引的值
  return currentVal ?? arr2[index];
});

如果需要优先取第二个数组的非空值,修改返回逻辑为return arr2[index] ?? currentVal即可。

Python 实现

# 取出对象中存储的两个数组
arr1, arr2 = obj
result = [a if a is not None else b for a, b in zip(arr1, arr2)]

如果需要优先取第二个数组的非空值,修改推导逻辑为[b if b is not None else a for a, b in zip(arr1, arr2)]即可。

内容的提问来源于stack exchange,提问作者rakshit

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 01:09:04