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

如何使用Lodash检查数组值是否存在于另一个数组中(附代码示例)

如何用Lodash检查数组值是否存在于另一个数组中

嘿,我来帮你梳理这个问题!从你的代码来看,你现在用了_.isEqual来对比数组,但如果你的需求是检查一个数组的元素是否存在于另一个数组(而不是完全相等),那得换个合适的Lodash方法。下面分情况给你调整代码:

先明确核心方法

Lodash里处理数组包含/交集的常用方法:

  • _.includes(array, value):判断单个值是否在目标数组里(适合传入的value是单个值的场景)
  • _.intersection(arr1, arr2):返回两个数组的交集,只要交集不为空,就说明有共同元素(适合传入的value也是数组的场景)
  • _.isEqual(arr1, arr2):严格对比两个数组的元素和顺序,只有完全一致才返回true——这是你当前用的,但如果是要判断"存在"而不是"完全相同",这个就不符合需求了

针对你的代码修改

场景1:传入的value是单个值,检查是否在category_ids的value数组中

把isEqual换成_.includes就行,这样就能判断单个值是否存在于目标数组里:

import { filter, includes } from 'lodash';

export const resolvers = {
  Query: {
    allItems: (_, { value }) => getAllLinks()
      .then(result => filter(result, val => 
        val.custom_attributes.find(customVal => 
          customVal.attribute_code === 'category_ids' && includes(customVal.value, value)
        )
      )),
  }
};

场景2:传入的value是数组,检查两个数组是否有共同元素

这种情况用_.intersection,只要交集长度大于0,就说明存在重叠元素:

import { filter, intersection } from 'lodash';

export const resolvers = {
  Query: {
    allItems: (_, { value }) => getAllLinks()
      .then(result => filter(result, val => 
        val.custom_attributes.find(customVal => 
          customVal.attribute_code === 'category_ids' && intersection(customVal.value, value).length > 0
        )
      )),
  }
};

场景3:你确实需要两个数组完全相等

如果你的需求就是判断category_ids的value和传入的value完全一致,那保留_.isEqual,但建议加个类型判断避免报错(毕竟你的Schema里CUSTOM_ATTRIBUTES是联合类型,value可能是字符串):

import { filter, isEqual } from 'lodash';

export const resolvers = {
  Query: {
    allItems: (_, { value }) => getAllLinks()
      .then(result => filter(result, val => 
        val.custom_attributes.find(customVal => 
          customVal.attribute_code === 'category_ids' && 
          Array.isArray(customVal.value) && 
          Array.isArray(value) && 
          isEqual(customVal.value, value)
        )
      )),
  }
};

额外注意:处理联合类型的安全问题

从你的Schema来看,CUSTOM_ATTRIBUTES是CustomString和CustomArray的联合类型,所以customVal.value可能是字符串或者数组。为了避免调用数组方法时报错,建议先判断customVal.value是数组类型再进行后续操作,就像上面场景3里加的Array.isArray(customVal.value)那样,这样能避免类型不匹配导致的意外错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:48:37