0

Say I have an array which consists of multiple duplicates

enter image description here

I wish to create a condition that looks at the ID and checks:

IF there is an object with multiple ID's AND this object also has a duplicate status AND duplicate dates, then console.log something

So in the table above, it should only show the object with the ID of 123, that has a status of ACTIVE and a date of 2023-01-01

Can you use indexOf for this purpose? I have used this method before with numbers, but as I said, in this case I don't want it to find ALL duplicates. I only want it to find duplicates that meet the conditions as stated above.

Cphml444
  • 85
  • 6
  • From your description it sounds like you want to remove duplicate objects from the array, as 'the conditions stated above' seem to cover the entire row. If so, this will help: https://stackoverflow.com/questions/2218999/how-to-remove-all-duplicates-from-an-array-of-objects – paddyfields Aug 16 '23 at 07:50
  • 4
    Also in future I'd recommend to tag your questions correctly - this question should presumably tagged as 'javascript', and is not 'vue' specific. You'll reach the right people that way. – paddyfields Aug 16 '23 at 07:55
  • 1
    Try this, seems similar https://stackoverflow.com/a/36744732/11722089 – Vikas Saini Aug 16 '23 at 09:44

1 Answers1

0

You can simply achieve this requirement by iterating the input array and with the help of Map object we can filtered out the duplicate keys and find out the desired result.

Live Demo :

const arr = [
  { id: 123, name: 'A', status: 'ACTIVE', date: '2023-01-01' },
  { id: 123, name: 'A', status: 'INACTIVE', date: '2023-02-01' },
  { id: 123, name: 'A', status: 'ACTIVE', date: '2023-01-01' },
  { id: 130, name: 'B', status: 'ACTIVE', date: '2023-01-01' },
  { id: 130, name: 'B', status: 'INACTIVE', date: '2023-02-01' },
  { id: 111, name: 'C', status: 'ACTIVE', date: '2023-01-01' }
];

function findDuplicateObjects(arr) {
  const duplicateMap = new Map();
  const duplicates = [];

  arr.forEach((item, index) => {
    const key = ['id', 'status', 'date'].map(prop => item[prop]).join('-');
      (duplicateMap.has(key)) ? duplicates.push(item) : duplicateMap.set(key, index);
    });
    
    return duplicates;
}

const duplicateObjects = findDuplicateObjects(arr);
console.log(duplicateObjects);
Debug Diva
  • 26,058
  • 13
  • 70
  • 123