0

Is there some simple way to write this block of code:

  this.markersDisplay = this.markersSource;

    // Filter Marker Type
    if (this.isValid(this.selectedMarkersType)) {
      let markers: Array<Marker> = new Array<Marker>();
      for (let marker of this.markersDisplay) {
        for (let markerType of this.selectedMarkersType) {
          if (marker.MarkerType == markerType) {
            markers.push(marker);
            break;
          }
        }
      }
      this.markersDisplay = markers;
    }

I would like to replace double for iteration with some lambda expression

Nemanja Andric
  • 625
  • 11
  • 30

4 Answers4

1

Try this:

markers = markersDisplay.filter(x=>{
    return selectedMarkersType.find((curVal,i)=>{
        return x.MarkerType==curVal;
    })
});
j4rey
  • 2,582
  • 20
  • 34
1

I made a couple of assumptions with regards to your data structure, but I hope the below code will work for you.

this.markersDisplay.forEach((p) => {
        p.MarkerType.filter(p => p.MarkerType === this.selectedMarkersType).map(p => markers.push(marker));
      });
Prasanth Mohan
  • 285
  • 1
  • 2
  • 12
1

If you don't need the break statement you can use this

markers = this.markersDisplay
    .filter((marker: Marker) => (this.selectedMarkersType
            .find((markerType: MarkerType) => markerType === marker.MarkerType)));

If you don't work with types:

markers = this.markersDisplay
    .filter(marker => (this.selectedMarkersType
            .find(markerType => markerType === marker.MarkerType)));

If you need to use the break statement for performance you can't use arrow functions. Instead, use some() or every() functions:

markers = this.markersDisplay
    .filter(marker => (this.selectedMarkersType
            .some(markerType => markerType === marker.MarkerType)));

You can see this happening in this stackblitz

Gaspar
  • 1,515
  • 13
  • 20
0

You want to use the Array.forEach method.

this.markersDisplay = this.markersSource;

// Filter Marker Type
if (this.isValid(this.selectedMarkersType)) {
  let markers: Array<Marker> = new Array<Marker>();
  this.markersDisplay.forEach(md => {
    this.selectedMarkersType.forEach(mt => {
      if (md.MarkerType === mt) {
        markers.push(md);
      }
    });
  });
  this.markersDisplay = markers;
}
The Head Rush
  • 3,157
  • 2
  • 25
  • 45