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

如何通过数字数组过滤嵌套数组的子项并获取目标输出(最优方案)

通过number对象过滤items数组获取目标结果

嘿,我来帮你搞定这个需求!首先得澄清一个小细节:你写的number其实更像是一个对象(数组没法用0: [0,1]这种键值对写法),假设它的实际结构是const number = {0: [0, 1], 1: [1], 2: [0]},我们可以用简洁高效的数组方法实现需求,这也是最优的解决方案哦~

原始数据定义

const items = [
  { name: "a", items: [ { name: "jack" }, { name: "jose" } ] },
  { name: "b", items: [ { name: "lara" }, { name: "jo" } ] },
  { name: "c", items: [ { name: "andy" }, { name: "hary" } ] }
];

const number = {0: [0, 1], 1: [1], 2: [0]}; // 修正为对象结构,匹配你的描述

最优实现代码

const filteredResult = items.map((group, index) => {
  // 取出当前分组对应的索引列表,映射为对应的name值
  return number[index].map(itemIdx => group.items[itemIdx].name);
});

console.log(filteredResult);
// 输出结果:[ ["jack", "jose"], ["jo"], ["andy"] ]

思路解释

  1. 用Array.map()遍历items数组的每个分组,同时获取分组的索引index
  2. 通过number[index]拿到当前分组需要保留的子项索引数组
  3. 再次用map()把索引数组转换为对应的name属性值
  4. 时间复杂度为O(n*m)(n是items的长度,m是每个number子数组的平均长度),这已经是最优复杂度了——毕竟我们必须遍历每一个需要保留的元素一次才能得到结果

另外提一句:你目标输出里的jole应该是笔误,正确的应该是jose,上面的代码已经给出了符合预期的结果哦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 01:09:07