comparing 2 array of objects is match irregardless of its indexes in lodash?

I have this array of objects I want to compare:

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'}];

As you can see the indexes of similar objects don't match. I want to check to see if every object in one array matches an object in the other array.

How do i achieve this in lodash? I was thinking of using map and sort in js, but i think it's not a good idea.

Upvotes: 0

Views: 65

Answers (2)

Isaac
Isaac

Reputation: 12874

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)

Alternatively, we can do a sorting based on key of your object. Sort both of them first, after sorted, we can use JSON.stringify to convert both and do comparison.

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370679

Could just compare each item stringifyed, that way it's just an every followed by .includes, no library needed:

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'}],
));

Upvotes: 1

Related Questions