Фильтр возвращает все, но должен возвращать только некоторые - PullRequest
0 голосов
/ 27 мая 2020

Я пишу функцию для ограничения результатов поиска по массиву объектов. Кажется, в основном работает ... но все же возвращает нежелательные объекты.

Вот мой код / ​​объяснение. Можете ли вы помочь мне понять, почему он все еще возвращает нежелательные объекты? определенные типы событий. Это прекрасно работает.

Второй .filter () - это то место, где у меня возникают проблемы. Это фильтрация групп, которые находятся в городе за 3 дня до выбранной даты выступления. Проблема в том, что даже несмотря на то, что console.log () работает в конце второго .filter (), он все равно возвращает полосу, даже если она не должна.

В приведенном ниже коде есть комментарии, объясняющие, что происходит.

    {
        bandTypes === "touring"
            ? tourBands
                .filter(band => {
                    if(showType !== 'Show Type'){
                        return band.showTypes.includes(showType)
                    }else {
                        return band
                    }
                })
                .filter(band => {
                    //User Clicks Button to Search within 3 days of the tourDate. This sets filterTourBandsByDate to true.

                    if(filterTourBandsByDate){

                        //Each Band may have more than 1 tour date.. so I now start filtering through all the tour dates. This Works.

                        band.bandTour.filter(tourDate => {

                            //Now I check to see if this tour date is within 100 miles of the savedLocation, which is their search location. This works.

                            let distanceToSearch = turf.distance(tourDate.geometry.coordinates, savedLocation, {units: 'miles'})    
                            if(distanceToSearch <= 100){

                                //If the specific tour location is within 100 miles of the saved location, I need to make sure that the tour location being filtered is actuall upcoming and not in the past.

                                let year = tourDate.geometry.tourDate.slice(0,4)
                                let month = tourDate.geometry.tourDate.slice(5, 7)
                                let day = tourDate.geometry.tourDate.slice(8)

                                let tourDateFormatted = new Date(year, month - 1, day)

                                //Check to make sure the tour date is upcoming - This works.

                                if(new Date() < tourDateFormatted ){
                                    //Now I am going to change the tour date to 3 days before the actual tour date. Then i'll check to see if the performanceDate (The users entered date) is past the new date. 

                                    tourDateFormatted.setDate(tourDateFormatted.getDate() - 3);

                                    if(performanceDate > tourDateFormatted ){
                                        console.log(tourDate)

                                        //Returns Correct Tour Date in the correct location. If I select a date that shouldnt return the band, the console.log does NOT fire, but it still returns the band.
                                        return band
                                    }
                                }
                            }
                        })

                    }else{
                        return band
                    }
                })
                .reduce(
                    (allPosts, band) =>
                        allPosts.concat(
                            (band.youtube.length > 0 &&
                                band.bandBio !== "n/a" &&
                                band.bandGenre !== "n/a")
                                ? band.posts.map((post) => ({ post, band }))
                                : []
                        ),
                    []
                )
                .sort((a, b) => new Date(b.post.date) - new Date(a.post.date))
                .slice(0, page * 10)
                .map(({ post, band }) => convertPost(post, band))
            : null
    }

1 Ответ

0 голосов
/ 27 мая 2020

Во второй функции .filter вы не всегда возвращаете значение. Вы выполняете операцию поиска с вызовом band.bandTour.filter(...), но возвращаемое вами значение не выскакивает наружу и не является результатом второй функции фильтра.

Вы сможете заменить это третье вложенный фильтр с al oop. В качестве альтернативы вы можете заменить этот третий вызов .filter(...) на .some(...) (поскольку вы пытаетесь определить, соответствует ли одно значение).

L oop версия:

.filter(band => {
  if(filterTourBandsByDate){
    for (const tourDate of band.bandTour) {
      let distanceToSearch = turf.distance(tourDate.geometry.coordinates, savedLocation, {units: 'miles'})    
      if(distanceToSearch <= 100){
        let year = tourDate.geometry.tourDate.slice(0,4)
        let month = tourDate.geometry.tourDate.slice(5, 7)
        let day = tourDate.geometry.tourDate.slice(8)

        let tourDateFormatted = new Date(year, month - 1, day)

        if(new Date() < tourDateFormatted ){
          tourDateFormatted.setDate(tourDateFormatted.getDate() - 3);
          return (performanceDate > tourDateFormatted);
        }
      }
    }
  } else {
    return true
  }
})

Версия объединения функций:

.filter(band => !filterTourBandsByDate || band.bandTour.some(tourDate => {
  let distanceToSearch = turf.distance(tourDate.geometry.coordinates, savedLocation, {units: 'miles'})    
  if(distanceToSearch <= 100){
    let year = tourDate.geometry.tourDate.slice(0,4)
    let month = tourDate.geometry.tourDate.slice(5, 7)
    let day = tourDate.geometry.tourDate.slice(8)

    let tourDateFormatted = new Date(year, month - 1, day)
    if(new Date() < tourDateFormatted ){
      tourDateFormatted.setDate(tourDateFormatted.getDate() - 3);
      return performanceDate > tourDateFormatted;
    }
  }
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...