rgdzv
rgdzv

Reputation: 505

How do I filter data with proper algorithm?

So I have that blocks of code:

const stops = {
  mainCheckBox : true,
  checkBox: {
    0: true,
    1: true,
    2: true,
    3: true
  }
}

const tickets = [
  {
    segments: [
      {
        stops: ['QWE', 'RTY', 'BGT']
      },
      {
        stops: ['CVB']
      }
    ]
  },
  ... // plus other same objects
]

What do I need? I need to filter them according to the length of stops + appropriate checkbox. For example: if I have chekcBox[0] true and legnth of the both stops arrays is 0, then I return the item.

So I wrote that algorithm:

const result = tickets.filter(item => {
  if (stops.mainCheckBox) return item
  if (stops.checkBox[0] && item.segments[0].stops.length === 0 && item.segments[1].stops.length === 0) return item
  if (stops.checkBox[1] && item.segments[0].stops.length === 1 && item.segments[1].stops.length === 1) return item
  if (stops.checkBox[2] && item.segments[0].stops.length === 2 && item.segments[1].stops.length === 2) return item
  if (stops.checkBox[3] && item.segments[0].stops.length === 3 && item.segments[1].stops.length === 3) return item
})

But that code looks bad and unacceptable. So without other libraries (like lodash and etc), how can I refactor the algorithm?

Upvotes: 1

Views: 114

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386881

You could take an array of key/indices and iterate with Array#some

const
    result = tickets.filter(item => 
        stops.mainCheckBox ||
        Object.keys(stops.checkBox).some(i =>
            stops.checkBox[i] &&
            item.segments[0].stops.length === +i &&
            item.segments[1].stops.length === +i
        )
    );

Upvotes: 1

Related Questions