yvl
yvl

Reputation: 670

Conditional filter function

I have a little problem with my filter function. I have a data structure as shown in the image below.

bridals array

As you can see, I have an array of objects named bridals and it keeps another array of objects named plans. So inside that I am trying to filter people.

Here is the filter function.

export function peopleFilter(bridals, people){
    if (people.length === 0) {
        return bridals;
    } else {
        bridals.forEach(bridal => {
            bridal.plans.filter((item) => {
                if (item.people === people) {
                    return bridals;
                }   
            })
        })

        return bridals;            
    }
}

The function peopleFilter() should filter plans with selected value only and return with bridals, but it returns nothing. No error is shown as well.

So I tried something like below.

bridals.forEach(bridal => {
    bridal.plans.slice().reverse().forEach((item, index, object) => {
        if (item.people !== people) {
            bridal.plans.splice(object.length - 1 - index, 1)                    
        }
    })
})

return bridals;

This above code is doing what I want. But there is one problem. So in the end when I select no value, it should display all plans. But it doesn't because I already removed the plans using splice() every time I select some value.

So I am stuck about this. How can I fix it?

Upvotes: 1

Views: 86

Answers (3)

Nidhin Joseph
Nidhin Joseph

Reputation: 10237

You need to return a boolean value inside the filter() instead of return bridals;. Additionally, this returned array needs to be reassigned to bridal array as well.

export function peopleFilter(bridals, people) {
  if (people.length === 0) {
    return bridals;
  } else {
    bridals.forEach(bridal => {
      bridal = bridal.plans.filter((item) => {
        return item.people === people;
      })
    })

    return bridals;
  }
}

Upvotes: 0

StackSlave
StackSlave

Reputation: 10617

Let's say you want to know the people count for all bridals and plans:

var total = 0;
bridals.forEach(function(b){
  b.plans.forEach(function(o){
    total += o.people;
  });
});

Of course, I can't really tell what you're trying to do. I could write an entire API for this.

Upvotes: 0

Greg Brodzik
Greg Brodzik

Reputation: 1817

In this case it might be easier to iterate over your bridal array with a map. Within the map, filter plans for each bridal, then return a new obj, which can be accomplished with spread syntax.

    const filterFunc = (bridals, people) => {
        return bridals.map(bridal => {
            const filteredPlans = bridal.plans.filter(plan => plan.people === people);
            return { ...bridal, plans: filteredPlans };
       })
    }

Upvotes: 1

Related Questions