mardi 18 octobre 2022

Taking 4 random objects from an array of objects and adding some extra properties to it

I want to implement a functionality where I want to take some selected objects totally in a random manner out of an array of objects. And then, add some extra properties to those selected objects by using a spread operator { extra properties, ...selected object}

Algorithm as follows

  1. Taking data as an array of objects (say an array consisting of 150 objects)
  2. Taking 4 random objects out of it based on their Id properties, but no two ids should match (say, it should not be 1, 2, 3, 1 , or 15, 67, 43, 67, they all should be unique , like 45, 67, 89, 12, and so on).
  3. pushing these 4 random objects into the new array, so that I could add the different properites to these 4 objects as per their index positions, inside this array.
  4. finally mapping the modified 4 objects to somewhere else, keeping the rest of (150) objects as it is.

so this is my logic...

const Data = [{
id : 1,
property : 'string1'
},
id : 2,
property : 'string2'
},
id : 3,
property : 'string3'
},
id : 4,
property : 'string4'
},
id : 1,
property : 'string5'
} ... and so on , till data.length;

//

for (let i = 0; i <= 3; i++){
var rand = Data[Math.floor(Math.random() * Data.length)];
console.log(rand); //but this is also giving me 2 duplicate objects, which I need to avoid, so how should I reframe this function?

}

    let newArr : any[] = [];
    newArr.push(rand); // i want all 4 objects to get stored into this array seperated by a comma, so that I could access them as per their index values

switch(newArr) {
case 0 : {(row : 4, col : 5, ...rand)};
break;
case 1 :  {(row : 3, col : 2, ...rand)};
break;
case 2 :  {(row : 1, col : 4, ...rand)};
break;
case 3 :  {(row : 3, col : 2, ...rand)};\
break;
default : 
}



//finally I would like to map these objects into my styled component...
<MyComponent>
Data.map(...)
</MyComponent>

I feel like < I am able to make you understand the solution I want to achieve.

In shortest possible words, 
"Out of an array of objects containing 500 objects or even more, I want to select only 4 random objects, 
then add few styling properties to those 4 objects using spread operator ..., and then map these 4 objects into <MyComponent />.

All suggestions are welcome and hereby appreciated in advance: )




Aucun commentaire:

Enregistrer un commentaire