本文介绍了与lodash对象比较深的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2阵,我会深深地 lodash

比较的对象

不过,我有一个概率与它:

 > VAR X = [{A:1,B:2},{C:3 D:4}]。
>变种Y = [{B:2,一个:1},{D:4,C:3}];
> _.difference(X,Y,_.isEqual);
[{A:1,B:2},{C:3 D:4}]

我应该

相比如何看到,无论是平等的?


解决方案

您可以使用比较,并调用的,以检查它们是否相等或没有。

\r
\r

VAR isArrayEqual =功能(X,Y){\r
  返回_(X).differenceWith(Y,_.isEqual).isEmpty();\r
};\r
\r
VAR RESULT1 = isArrayEqual(\r
  [{A:1,B:2},{C:3 D:4}],\r
  [{B:2,一个:1},{D:4,C:3}]\r
);\r
\r
VAR RESULT2 = isArrayEqual(\r
  [{A:1,B 2,C:1},{C:3 D:4}],\r
  [{B:2,一个:1},{D:4,C:3}]\r
);\r
\r
文件撰写([\r
  '< D​​IV><标签> RESULT1:,RESULT1,'< /标签>< / DIV>,\r
  '< D​​IV><标签>结果2:',结果2,'< /标签>< / DIV>,\r
]。加入(''));

\r

&LT;脚本src=\"https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.js\"></script>\r
\r
\r

I've 2 array of objects that I'd deeply compare with lodash

However, I've a prob with it:

> var x = [{a:1, b:2}, {c:3, d:4}];
> var y = [{b:2, a:1}, {d:4, c:3}];
> _.difference(x,y, _.isEqual);
[ { a: 1, b: 2 }, { c: 3, d: 4 } ]

How should I compare to see that both are equal?

解决方案

You can make use of differenceWith() with an isEqual() comparator, and invoke isEmpty to check if they are equal or not.

var isArrayEqual = function(x, y) {
  return _(x).differenceWith(y, _.isEqual).isEmpty();
};

var result1 = isArrayEqual(
  [{a:1, b:2}, {c:3, d:4}],
  [{b:2, a:1}, {d:4, c:3}]
);

var result2 = isArrayEqual(
  [{a:1, b:2, c: 1}, {c:3, d:4}],
  [{b:2, a:1}, {d:4, c:3}]
);

document.write([
  '<div><label>result1: ', result1, '</label></div>',
  '<div><label>result2: ', result2, '</label></div>',
].join(''));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.js"></script>

这篇关于与lodash对象比较深的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 05:23