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

JavaScript如何筛选数组中和为10的元素对按序存入新数组

数组和为10配对问题修复

问题需求

给定数组 arr = [2,4,8,7,3,6],找出数组中两两相加和为10的元素,将配对的两个元素相邻排列后存入新数组arr2,要求配对元素相邻放置,示例预期结果为 arr2 = [2,8,3,7,4,6]。

原代码错误点

  • 数组长度写法错误:JS中数组的length是属性,不是方法,写arr.length()会直接抛出类型错误
  • 匹配逻辑错误:仅比较相邻位置的两个元素,无法匹配到不相邻但和为10的组合(比如索引0的2和索引2的8)
  • 存入值错误:indexOf返回的是元素索引,不是元素本身,存入索引不符合需求
  • 无去重逻辑:没有标记已配对的元素,会出现元素重复配对、重复存入的问题
  • 打印逻辑错误:arr2是成对插入元素,按原数组索引i取值会频繁拿到undefined

可运行实现代码

版本1:按数组遍历顺序配对(核心功能实现)

该版本按照元素在原数组中出现的顺序配对,保证配对元素相邻,逻辑简单易读:

const arr = [2, 4, 8, 7, 3, 6];
const arr2 = [];
const targetSum = 10;
// 标记对应索引的元素是否已经完成配对
const isPaired = new Array(arr.length).fill(false);

for (let i = 0; i < arr.length; i++) {
  if (isPaired[i]) continue;
  const current = arr[i];
  // 找当前元素对应的补数(和为10的另一个数)
  const matchNum = targetSum - current;
  // 从i的下一位开始查找,避免重复配对
  for (let j = i + 1; j < arr.length; j++) {
    if (!isPaired[j] && arr[j] === matchNum) {
      arr2.push(current, matchNum);
      isPaired[i] = true;
      isPaired[j] = true;
      break;
    }
  }
}

console.log(arr2); // 输出 [2,8,4,6,7,3]

版本2:匹配示例输出顺序

如果需要完全得到给出的[2,8,3,7,4,6]结果,只需要在配对完成后,对每一组配对按「小值在前、组间按小值升序」的规则排序即可:

const arr = [2, 4, 8, 7, 3, 6];
const targetSum = 10;
const pairs = [];
const isPaired = new Array(arr.length).fill(false);

for (let i = 0; i < arr.length; i++) {
  if (isPaired[i]) continue;
  const current = arr[i];
  const matchNum = targetSum - current;
  for (let j = i + 1; j < arr.length; j++) {
    if (!isPaired[j] && arr[j] === matchNum) {
      // 每对存的时候保证小值在前
      const pair = current < matchNum ? [current, matchNum] : [matchNum, current];
      pairs.push(pair);
      isPaired[i] = true;
      isPaired[j] = true;
      break;
    }
  }
}
// 组间按每对第一个元素升序排列后扁平化得到一维数组
const arr2 = pairs.sort((a,b) => a[0] - b[0]).flat();

console.log(arr2); // 输出 [2,8,3,7,4,6],和预期完全一致

内容的提问来源于stack exchange,提问作者Rom-san

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 14:54:19