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

如何用functional programming在数组元素间插入由相邻元素生成的新元素?

在数组相邻元素间插入推导对象的函数式实现

基础纯函数实现(原生JavaScript)

利用reduce完成累积式构建,这是函数式编程中处理这类问题的经典方式:

const intersperseDerived = (arr, derive) => {
  if (arr.length <= 1) return [...arr];
  return arr.reduce((acc, curr, idx) => {
    if (idx === 0) return [curr];
    const prev = acc.at(-1);
    return [...acc, derive(prev, curr), curr];
  }, []);
};

// 测试加法推导的场景
const input = [1, 2, 3];
const output = intersperseDerived(input, (a, b) => a + b);
console.log(output); // [1, 3, 2, 5, 3]
  • derive参数是自定义推导函数,你可以根据实际场景替换(比如处理对象时提取属性计算、拼接等)
  • 函数是纯函数,不会修改原数组,输入相同则输出一致
  • 处理了数组长度≤1的边界情况

用函数式工具库简化(Ramda.js)

如果项目中使用Ramda,结合zipWith和interleave可以更简洁地实现:

const R = require('ramda');

const intersperseDerived = R.curry((derive, arr) => {
  if (arr.length <= 1) return arr;
  const derived = R.zipWith(derive, arr, R.tail(arr));
  return R.interleave(arr, derived);
});

// 测试
intersperseDerived((a, b) => a + b, [1,2,3]); // [1, 3, 2, 5, 3]
  • zipWith生成所有相邻元素对的推导结果数组
  • interleave将原数组和推导数组合并,自动完成穿插
  • 用curry实现柯里化,方便复用推导逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 08:45:35