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

JavaScript多维数组筛选:能否提取含candy分类的元素?

解决方案:过滤包含指定分类的数组元素

当然可以实现!在JavaScript中,我们可以利用Array.filter()方法结合Array.includes()来快速筛选出符合条件的元素,完全不需要复杂的逻辑。

具体实现代码

// 你的原始数组
const posts = [
  {ID: 141, categories: ["candy", "fruits", "vegetables"]},
  {ID: 142, categories: ["fruits"]},
  {ID: 143, categories: ["candy", "vegetables"]}
];

// 过滤出categories数组包含"candy"的元素
const candyRelatedPosts = posts.filter(post => post.categories.includes('candy'));

// 输出结果
console.log(candyRelatedPosts);

代码说明

  • filter():这是数组的高阶方法,会遍历原数组的每一项,将返回值为true的项收集起来,形成一个新数组返回(不会修改原数组,这一点很友好)。
  • includes():用于判断数组中是否存在指定的元素,存在则返回true,否则返回false,正好作为filter()的判断条件。

兼容旧环境的替代方案

如果你的运行环境不支持includes()(比如非常旧的浏览器),可以用indexOf()替代:

const candyRelatedPosts = posts.filter(post => post.categories.indexOf('candy') !== -1);

indexOf()会返回元素在数组中的索引,找不到则返回-1,所以判断索引不等于-1就代表元素存在。

运行上面的代码后,candyRelatedPosts就是你期望的新数组啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:22:33