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

如何用函数链式调用实现JavaScript嵌套数组逐元素减法

嵌套数组的逐元素减法(函数式链式调用实现)

我是JavaScript新手,希望使用函数链式调用对两个维度相同的嵌套数组进行逐元素减法操作。我的数据结构如下:

const data_1 = [["0", ["foo", 10]], ["1", ["bar", 15]], ["2", ["baz", 20]]];
const data_2 = [["0", ["foo", 8]], ["1", ["bar", 17]], ["2", ["baz", 10]]];

期望得到结果:

const data_result = [["0", ["foo", 2]], ["1", ["bar", -2]], ["2", ["baz", 10]]];

若数组无多层嵌套,我可使用map方法实现,但嵌套结构下该如何用函数式方式达成需求?

实现方案

因为两个数组结构完全一致,我们可以通过嵌套的map方法,结合函数式的纯逻辑处理来实现需求:

基础实现代码

const data_1 = [["0", ["foo", 10]], ["1", ["bar", 15]], ["2", ["baz", 20]]];
const data_2 = [["0", ["foo", 8]], ["1", ["bar", 17]], ["2", ["baz", 10]]];

const data_result = data_1.map((item1, index) => {
  const item2 = data_2[index];
  // 处理内层嵌套数组,只对数字执行减法
  const processedNested = item1[1].map((val, nestedIdx) => 
    typeof val === 'number' ? val - item2[1][nestedIdx] : val
  );
  // 返回新的外层数组项,不修改原数据
  return [item1[0], processedNested];
});

console.log(data_result);
// 输出:[["0", ["foo", 2]], ["1", ["bar", -2]], ["2", ["baz", 10]]]

链式风格优化(复用性更强)

如果想要更纯粹的链式调用写法,可以把核心逻辑抽成独立函数:

// 定义处理单组嵌套元素的纯函数
const subtractPair = (item2) => (item1) => [
  item1[0],
  item1[1].map((val, idx) => 
    typeof val === 'number' ? val - item2[1][idx] : val
  )
];

// 链式调用map完成计算
const data_result = data_1.map((item, idx) => subtractPair(data_2[idx])(item));

核心逻辑说明

  • 利用map的第二个参数index,精准关联两个数组的同位置元素
  • 内层map专门处理嵌套数组,通过类型判断确保只有数字执行减法操作,字符串标识(如"foo")原样保留
  • 全程使用纯函数,不会修改原始数组,符合函数式编程的无副作用要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 11:41:05