vendredi 1 décembre 2023

Map an activerecord array to avoid that two item with the same attribute are in a sequential position

I have an issue to solve.

I have an array of elements, and on each element I can call the method 'content.sponsored?' that return me true or false.

The items that return true are 2/3 every 20 elements and they are always in the first position.

I need to map this array to avoid consecutive 'true'.

For example

contents = [
  { id: 1, sponsored: true },
  { id: 2, sponsored: true },
  { id: 3, sponsored: false },
  { id: 4, sponsored: false },
  { id: 5, sponsored: false },
  { id: 6, sponsored: false }...
]

I need

contents = [
  { id: 1, sponsored: true },
  { id: 2, sponsored: false },
  { id: 3, sponsored: true },
  { id: 4, sponsored: false },
  { id: 5, sponsored: false },
  { id: 6, sponsored: false }...
]

Which is the most efficient way to map these elements?

Aucun commentaire:

Enregistrer un commentaire