1

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?

1
  • Are you going to filter and find duplicates with key you know. In above example, x will be your unique key that can be passed to find duplicates? Commented Aug 13, 2020 at 5:53

3 Answers 3

2

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}]
Sign up to request clarification or add additional context in comments.

1 Comment

In case of multiple (more than 2) occurrences of similar objects you might have to apply another _.uniqWith() on the result.
0

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));

1 Comment

I want to achieve it using lodash
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.