Home > OS >  How to compare and filter two different JS objects that one to many relationship
How to compare and filter two different JS objects that one to many relationship

Time:12-16

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

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'}].

CodePudding user response:

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)

  • Related