比较2个对象数组是否匹配,无论其在lodash中的索引?

时间:2018-05-28 08:00:42

标签: javascript lodash

我想要比较这个对象数组:

const arr1 = [{a:'first', b:'second'}, {c:'third', d: 'fourth'}, {e:'fifth', f: 'sixth'}];
const arr2 = [{c:'third', d: 'fourth'},  {e:'fifth', f: 'sixth'}, {a:'first', b:'second'}];

正如您所看到的,类似对象的索引不匹配。我想检查一个数组中的每个对象是否与另一个数组中的对象匹配。

我如何在lodash中实现这一目标?我想在js中使用map和sort,但我认为这不是一个好主意。

2 个答案:

答案 0 :(得分:1)

可以只比较每个项目stringify,这样只需every后跟.includes,无需图书馆:



const arrsMatch = (arr1, arr2) => {
  const arr2Strings = arr2.map(JSON.stringify);
  return arr1.every(item => arr2Strings.includes(JSON.stringify(item)));
};
console.log(arrsMatch(
  [{a:'first', b:'second'}, {c:'third', d: 'fourth'}, {e:'fifth', f: 'sixth'}],
  [{c:'third', d: 'fourth'},  {e:'fifth', f: 'sixth'}, {a:'first', b:'second'}],
));
console.log(arrsMatch(
  [{a:'DOESNT-MATCH', b:'second'}, {c:'third', d: 'fourth'}, {e:'fifth', f: 'sixth'}],
  [{c:'third', d: 'fourth'},  {e:'fifth', f: 'sixth'}, {a:'first', b:'second'}],
));




答案 1 :(得分:1)



const arr1 = [{a:'first', b:'second'}, {e:'fifth', f: 'sixth'}, {c:'third', d: 'fourth'}];
const arr2 = [{c:'third', d: 'fourth'},  {e:'fifth', f: 'sixth'}, {a:'first', b:'second'}];


let match = JSON.stringify(arr1.sort((x, y) => {
              return Object.keys(x)[0] > Object.keys(y)[0]})) 
         === 
         JSON.stringify(arr2.sort((x, y) => {
           return Object.keys(x)[0] > Object.keys(y)[0]}))
console.log(match)




或者,我们可以根据您对象的键进行排序。首先对它们进行排序,排序后,我们可以使用JSON.stringify转换它们并进行比较。