Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I obtain a list of IDs from L1 that do not include all the elements from the second array L2?

let L1 = [
    { id: 1, name: 'Object 1' },
    { id: 1, name: 'Object 2' },
    { id: 1, name: 'Object 3' },

    { id: 2, name: 'Object 1' },
    { id: 2, name: 'Object 2' },
    
    { id: 3, name: 'Object 1' },
    { id: 3, name: 'Object 3' }  
];

// Second array
let L2 = ['Object 1', 'Object 3'];

let idsWithMissingNames = L1.reduce((result, item) => {
  if (!L2.includes(item.name)) {
      result.push(item.id);
  }
  return result;
}, []);

console.log(idsWithMissingNames);
//expected result is: 2

I included my code as well but it doesn’t work.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Since it is an exclusion AND check, you need to do some pre processing to get the data into a format that it is easy to loop over and find the matches. So create an object with arrays that holds the name.

You will loop over this object and look for all the keys that match. If they all match you exclude it.

let L1 = [
    { id: 1, name: 'Object 1' },
    { id: 1, name: 'Object 2' },
    { id: 1, name: 'Object 3' },

    { id: 2, name: 'Object 1' },
    { id: 2, name: 'Object 2' },
    
    { id: 3, name: 'Object 1' },
    { id: 3, name: 'Object 3' }  
];

let L2 = ['Object 1', 'Object 3'];

// combine all of he names into an array so it is easy look up
const groupedNamesById = L1.reduce((acc, obj) => {
    acc[obj.id] = acc[obj.id] || [];
    acc[obj.id].push(obj.name);
    return acc;
}, {});

// Loop over your groups of ids to find the items that do not have all matches
const nonMatchIds = Object.entries(groupedNamesById).reduce((ids, entry) => {
  // do all of the names exist for this group? If no, add it to the list
  if (!L2.every(name => entry[1].includes(name))) {
    ids.push(entry[0]);
  }
  return ids;
}, []);

// Display your group
console.log(nonMatchIds);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading