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

如何利用两个一维数组生成指定结构对象并获取关联值?

问题与解决方案

原始数据与需求

给定两个一一对应的数组:

let x = [1,2,0,4,7,8,9,1,1,1];
let y = [10,50,80,70,906,80,70,80,15,11]

需求如下:

  • 找出数组x中大于0的最小值和最大值;
  • 获取与这两个值对应的所有y数组元素;
  • 获取数组x中所有0对应的y数组元素;
  • 将结果整理为指定结构的对象:
let res = { 
  min: {
    minVal: 1,
    minvalues: [10, 80, 15, 11]
  },
  max:  {
    minVal: 9,
    minvalues: [70]
  },
  empty: [80]
}

现有代码的问题

你当前用map生成的res是一组键值对对象,后续用filter只能筛选出包含对应键的对象,无法直接拿到y的值;同时逻辑未串联完整需求,比如未处理empty部分,也没正确提取对应y数组元素。

正确实现方案

完整代码

let x = [1,2,0,4,7,8,9,1,1,1];
let y = [10,50,80,70,906,80,70,80,15,11];

// 筛选x中大于0的元素,计算最小最大值
const positiveX = x.filter(num => num > 0);
const minVal = Math.min(...positiveX);
const maxVal = Math.max(...positiveX);

// 提取对应y数组元素
const minYValues = y.filter((_, index) => x[index] === minVal);
const maxYValues = y.filter((_, index) => x[index] === maxVal);
const emptyYValues = y.filter((_, index) => x[index] === 0);

// 构建目标结构对象
const res = {
  min: {
    minVal: minVal,
    minvalues: minYValues
  },
  max: {
    minVal: maxVal,
    minvalues: maxYValues
  },
  empty: emptyYValues
};

console.log(res);

代码说明

  • 通过filter筛选出x中大于0的元素,再用Math.min和Math.max快速得到目标极值;
  • 利用filter结合索引判断,直接从y数组提取对应条件的元素,避免生成多余的中间对象;
  • 逻辑清晰直接,最终生成的对象完全符合需求指定的结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 22:40:24