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

如何基于cars数组正确过滤inventory数组?当前返回空数组

问题解决:基于cars数组过滤inventory数组

你的代码问题出在val.customers.map(val => val.model)返回的是一个数组,而cars.includes()是用来判断单个元素是否存在于数组中的,数组和字符串无法匹配,导致过滤条件始终为false,最终得到空数组结果。

修正方法是用Array.some()替代map(),some()会检查数组中是否至少有一个元素满足条件——只要当前inventory项的customers里有任意一个model存在于cars数组中,就保留这个inventory项:

const cars = ['s', 'y']

const inventory = [{
  desc: 'Tesla',
  customers: [{
    model: 's',
    name: 'John'
  }]
}, {
  desc: 'Audi',
  customers: [{
    model: 'q3',
    name: 'Doe'
  }]
}]

const result = inventory.filter((item) => {
  // 检查当前inventory项的customers中是否有model在cars数组内
  return item.customers.some(customer => cars.includes(customer.model))
})

console.log(result)

运行这段代码后,就能得到你期望的结果:

[{
  desc: 'Tesla',
  customers: [{
    model: 's',
    name: 'John'
  }]
}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 23:23:16