Home > Software design >  javascript make a Set for each attribute in a Map of Objects in Single Iteration
javascript make a Set for each attribute in a Map of Objects in Single Iteration

Time:10-11

Here what is going on. I've got 4 objects. objA, objB, objC, objD.

objD, has multiple attributes and between them, objA, objB and objC.

class objD{
   constructor(objA, objB, objC, otherAttributes...){
        this.objA = objA;
        this.objB = objB;
        this.objC = objC;
        this.otherAttributes = otherAttributes;
        ...
   }
}

I have a Map() for each objAs, Bs, Cs as well as the objDs.

But, I've got to filter only the objAs, Bs and Cs that are used in objDs. After all, not all objAs, Bs and Cs are used, so, there is no point showing them in my options.

So, What I'm trying to achieve: Have 3 Sets from the used objAs, objBs, and objCs in a single Iteration. Of course that I could iterate 3 times the map of ObjDs. But I'd like to do that in a single iteration.

Here is what I've done so far:

To do a set of objAs for example:

let mapOfObjDs;  //this is the map containing all the objDs.
let setOfObjAs = new Set(Array.from(mapOfObjDs.values(), (x) => x.objA))

I manage to get an array 3 x n(n is the number of objDs):

 let map = Array.from(mapOfObjDs.values()).map((x) => 
        [
            x.objA,
            x.objB,
            x.objC
        ]);

But I have no Idea of how to convert this to 3 sets without iterating 3 times. Is it possible to do that in a single iteration?

CodePudding user response:

You could create an array of sets and iterate the mapOfObjDs to insert each value.

For example:

// Map of objects
let mapOfObjDs = new Map([
    ["1", new objD("a1","b1","c1")],
    ["2", new objD("a2","b2","c2")],
    ["3", new objD("a3","b3","c3")],
    ["4", new objD("a4","b4","c4")]
]);

// Create empty array of set
let arrOfObjs = Array.from({length: 3}, (e) => new Set());

// Insert values
for (const objd of mapOfObjDs.values()) {
    arrOfObjs[0].add(objd.objA);
    arrOfObjs[1].add(objd.objB);
    arrOfObjs[2].add(objd.objC);
}

console.log(arrOfObjs);

output:

[
  Set(4) { 'a1', 'a2', 'a3', 'a4' },
  Set(4) { 'b1', 'b2', 'b3', 'b4' },
  Set(4) { 'c1', 'c2', 'c3', 'c4' }
]

CodePudding user response:

Something like this?

class objD{
   alldata = {
     A: new Set(),
     B: new Set(),
     C: new Set()
   }

   constructor(objA, objB, objC, otherAttributes...){
        this.objA = objA;
        this.objB = objB;
        this.objC = objC;
        this.otherAttributes = otherAttributes;
        
        alldata.A.add(objA);
        alldata.B.add(objB);
        alldata.C.add(objC);
   }
}

Then later you can access the lists via objD.alldata.A etc

  • Related