比较与订单无关的对象数组 [英] Compare arrays of objects independent of the order

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

问题描述

我有2个对象数组,我必须比较它们,但对象的顺序不是很重要。我不能对它们进行排序,因为我没有它们的键名,因为这些函数必须是通用的。我对数组的唯一信息是两个数组的对象具有相同数量的键,并且这些键具有相同的名称。所以array1必须包含与array2相同的对象。

I have 2 arrays of objects and I have to compare them, but the order of the objects DOES NOT matter. I can't sort them because I won't have their keys' names because the functions must be generic. The only information that I'll have about the array is that both array's objects have the same amount of keys and those keys have the same name. So the array1 must contain the same objects as the array2.

var array1 = [{"key1":"Banana", "key2":"Yammy"}, {"key1":"Broccoli", "key2":"Ew"}];
var array2 = [{"key1":"Broccoli", "key2":"Ew"}, {"key1":"Banana", "key2":"Yammy"}];

在示例中,array1必须等于array2。
我尝试使用chai .eql()方法,但它不起作用。

In the example, array1 must be equal array2. I tryed to use the chai .eql() method but it didn't work.

推荐答案

您可以 array #join 分隔符上对象的每个值,然后生成一个新的字符串数组,然后使用比较每个值 array#every array#includes

You can array#join each value of the object on an separator and then generate a new array of string and then compare each values using array#every and array#includes

var array1 = [{"key1":"Banana", "key2":"Yammy"}, {"key1":"Broccoli", "key2":"Ew"}];
    array2 = [{"key1":"Broccoli", "key2":"Ew"}, {"key1":"Banana", "key2":"Yammy"}];
    values = (o) => Object.keys(o).sort().map(k => o[k]).join('|'),
    mapped1 = array1.map(o => values(o)),
    mapped2 = array2.map(o => values(o));

var res = mapped1.every(v => mapped2.includes(v));

console.log(res);

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆