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

如何用JavaScript/Lodash判断数组对象是否全部存在于另一数组?

如何判断数组中所有对象都存在于另一个对象数组中?

我懂你折腾了好几个小时的心情——就是要一个干脆的布尔值,用来确认待比较数组里的每一个对象,是不是都能在compareWith数组里找到完全匹配的。先再明确下你的预期结果:

  • [{b:2}] → true({b:2}在compareWith里)
  • [{c:3},{a:1}] → true(两个对象都在compareWith里)
  • [{a:1},{b:2}] → true(两个对象都在compareWith里)
  • [{a:1},{d:3}] → false({d:3}不在compareWith里)

你之前用了Lodash的_.differenceWith,但它返回的是差集数组,不是你要的布尔值。其实只要稍作改造,或者换个API组合就能搞定。

方案一:基于_.differenceWith改造(简洁直观)

_.differenceWith(targetArr, compareWith, _.isEqual)会返回待比较数组targetArr中,所有不在compareWith里的对象。如果这个差集数组的长度是0,就说明targetArr里的所有对象都在compareWith中:

import _ from 'lodash';

const compareWith = [{a:1},{b:2},{c:3}];

// 批量测试所有用例
const testCases = [
  [{b:2}],
  [{c:3},{a:1}],
  [{a:1},{b:2}],
  [{a:1},{d:3}]
];

testCases.forEach(test => {
  const isAllExist = _.differenceWith(test, compareWith, _.isEqual).length === 0;
  console.log(`测试数组${JSON.stringify(test)} → ${isAllExist}`);
});

运行后会输出:

测试数组[{"b":2}] → true
测试数组[{"c":3},{"a":1}] → true
测试数组[{"a":1},{"b":2}] → true
测试数组[{"a":1},{"d":3}] → false

方案二:用_.every + _.some组合(逻辑清晰)

如果想更直白地体现“所有元素都满足存在条件”的逻辑,可以用_.every遍历待比较数组,再用_.some检查当前对象是否在compareWith中有匹配(_.isEqual用来做深度对象相等判断):

import _ from 'lodash';

const compareWith = [{a:1},{b:2},{c:3}];

const isAllObjectsExist = (targetArr) => {
  return _.every(targetArr, targetItem => {
    return _.some(compareWith, compareItem => _.isEqual(targetItem, compareItem));
  });
};

// 逐个测试用例
console.log(isAllObjectsExist([{b:2}])); // true
console.log(isAllObjectsExist([{c:3},{a:1}])); // true
console.log(isAllObjectsExist([{a:1},{b:2}])); // true
console.log(isAllObjectsExist([{a:1},{d:3}])); // false

这两种方案都能完美满足你的需求,选哪个看你更偏好简洁写法还是直白的逻辑表达~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 17:47:51