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 to compare and filter two different JS objects that one to many relationship

I have two different JS objects and I want to compare and filter them, like I need to compare clusters with pathways and finally clusters must be only that are mapped to pathways.

const pathways = [{area: 1, clusterId: 1},{area: 2, clusterId: 4}];
const clusters = [{id:1,name:'london'},{id:2, name: 'paris'},{id:3, name:'rome'},{id:4, name: 'brussel'}];


And expected result when I print cluster is [{id:1,name:’london’}, {id:4, name: ‘brussel’}].

Here is what I tried

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

let pathways = [{id: 1, clusterId: 1},{id: 2, clusterId: 4}];
let clusters = [{id:1,name:'london'},{id:2, name: 'paris'},{id:3, name:'rome'},{id:4, name: 'brussel'}];

clusters = clusters.filter((cluster, i) => {
           if (cluster.id === pathways[i].clusterId) {
              return clusters;
            }
  
          });

console.log(clusters);

But I am getting Error: Cannot read properties of undefined (reading ‘clusterId’), can some help me?

What I tried

let pathways = [{id: 1, clusterId: 1},{id: 2, clusterId: 4}];
let clusters = [{id:1,name:'london'},{id:2, name: 'paris'},{id:3, name:'rome'},{id:4, name: 'brussel'}];

clusters = clusters.filter((cluster, i) => {
           if (cluster.id === pathways[i].clusterId) {
              return clusters;
            }
  
          });

console.log(clusters);

And what I expect cluster = [{id:1,name:’london’}, {id:4, name: ‘brussel’}].

>Solution :

Two lists = two loops

const pathways = [{area: 1, clusterId: 1},{area: 2, clusterId: 4}];
const clusters = [{id:1,name:'london'},{id:2, name: 'paris'},{id:3, name:'rome'},{id:4, name: 'brussel'}];

const filtered = clusters.filter(cluster => pathways.some(pathway => pathway.clusterId === cluster.id))
console.log(filtered)
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