0

i have dropdown values at frontend as follows. You can see the first 2 values Mar and May are checked based off the checked property in dropdownValues below.

let dropdownValues = [ 
{key: 'Mar', checked: true},
{key: 'May', checked: true}, 
{key: 'June', checked: false} 
]

This is the input i am getting from backend.

let input  = [
    {month: "Mar", count: "45"}, 
    {month: "May", count: "12"}, 
    {month: "June", count: "5"} 
]

So based off of the dropdown values, i want to filter the input and get the output as follows. Notice the June month object is removed at output because June key has checked false in the dropdownValues

output = [ 
    {month: "Mar", count: "45"}, 
    {month: "May", count: "12"} 
]

In order to achieve this result, i do the following

let output = input?.filter((el) => {
        return dropdownValues.some((f) => {
          return f.checked;
        });
      });

But this doesnot filter out properly. can someone help me or let me know where i am going wrong.

2 Answers 2

1

You're not searching for the matching key property in dropdownValues.

let dropdownValues = [{ key: 'Mar', checked: true }, { key: 'May', checked: true }, { key: 'June', checked: false }]; 

let input = [{ month: "Mar", count: "45" }, { month: "May", count: "12" }, { month: "June", count: "5" }];

let output = input.filter(({month}) => dropdownValues.find(({key,checked}) => key == month && checked));

console.log(JSON.stringify(output));

1

Alternatively for the above solution, you can also come up with another approach using Array.prototype.includes() method.

Refer the below code which adopts the includes method:

let dropdownValues = [{ key: 'Mar', checked: true }, { key: 'May', checked: true }, { key: 'June', checked: false }];

let input = [{ month: "Mar", count: "45" }, { month: "May", count: "12" }, { month: "June", count: "5" }];

let output = input.filter(item => 
    dropdownValues.filter(d => d.checked).map(d => d.key).includes(item.month)
);

console.log(JSON.stringify(output));

Not the answer you're looking for? Browse other questions tagged or ask your own question.