TechChain
TechChain

Reputation: 8944

FInd duplicates withtin array based on certain keys using lodash?

I have an array like this

let data = [{x:1,y:2,z:3},{x:1,y:2,z:3},{x:1,y:2,z:4},{x:11,y:2,z:3}]

Now I want to get only those items whose x,y,z values are the same.so expected output should be

{x:1,y:2,z:3}

Because {x:1,y:2,z:3} has duplicate values but rest of them not so I don't want to get rest of them because they do not have any duplicates. Please tell me how can I achieve this?

Upvotes: 1

Views: 317

Answers (3)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

Build an object to track the duplicates and use Object.values and filter

let data = [
  { x: 1, y: 2, z: 3 },
  { x: 1, y: 2, z: 3 },
  { x: 1, y: 2, z: 4 },
  { x: 11, y: 2, z: 3 },
];

const all = {};
data.forEach(({ x, y, z }) => {
  const key = `x${x}y${y}z${z}`;
  all[key] = key in all ? { x, y, z } : null;
});

const res = Object.values(all).filter(Boolean);

console.log(res);

Upvotes: 0

Shadab
Shadab

Reputation: 1347

For lodash 4.17.15,

You can first use _.uniqWith and _.isEqual to find the unique values.

_.uniqWith(data, _.isEqual); // [{x:1,y:2,z:3},{x:1,y:2,z:4},{x:11,y:2,z:3}] 

Then use _.difference to remove the unique values from the array, leaving just the duplicates

_.difference(data, _.uniqWith(data, _.isEqual)); // [{x:1,y:2,z:3}]

Upvotes: 2

Ilijanovic
Ilijanovic

Reputation: 14904

let data = [{x:1,y:2,z:3},{x:1,y:2,z:3},{x:1,y:2,z:4},{x:11,y:2,z:3},{x:11,y:2,z:3}]

function filterDuplicates(data) {
   let dic = {};
   data.forEach(obj => {
      let strObj = JSON.stringify(obj, Object.keys(obj).sort());
      if(strObj in dic) {
         ++dic[strObj];
         return;
      }
      dic[strObj] = 0;
   })
   return Object.entries(dic).filter(([key, value]) => value > 0).map(([el]) => JSON.parse(el));
   
}

console.log(filterDuplicates(data));

Upvotes: 0

Related Questions