Scenario: I am working with a multiselect dropdown where users can select multiple object values. Each object contains a string value that needs to be compared against. The selections made are then separated into different arrays based on predefined parameters for later use with an API call.
Challenge: Despite attempting to loop through the selections and match them with the parameters, I found that the order of selection and parameters affects the outcome. They only align if they happen to be in sync during the looping process.
To demonstrate this issue, I have provided a stackblitz example. It showcases the data model and logic used, allowing you to understand the issue by triggering the function with mock data via a button click and viewing the console logs for the outputs.
Desired Result:
SELECTION:
mockSelections = [
{
id: "4",
type: "I_am_BLUE"
},
{
id: "1",
type: "I_am_RED"
},
{
id: "2",
type: "I_am_GREEN"
},
{
id: "3",
type: "I_am_BLUE"
}
];
EXPECTED OUTPUT:
this.filterState = {
I_am_RED: [
{
id: "1",
type: "I_am_RED"
}
],
I_am_GREEN: [
{
id: "2",
type: "I_am_GREEN"
}
],
I_am_BLUE: [
{
id: "3",
type: "I_am_BLUE"
},
{
id: "4",
type: "I_am_BLUE"
}
]
};
The desired output arranges selections with "I_am_BLUE" in the "I_am_BLUE" array, ensuring each group is correctly sorted.
FUNCTION:
handleFilterChange(prop: string, value: any): void {
let field = this.fields.find(f => f.name === prop);
if (field.params) {
console.log("FIELD PARAMS", field.params);
console.log("SELECTED VALUES", value);
field.params.forEach((param, i) => {
// additional double looping logic required here?
if (value[i].type === param) {
this.setFilterState(param, value[i], field);
}
});
} else {
this.setFilterState(prop, value, field);
}
console.log("SUBMITTED SORTED VALUES", this.filterState);
}
Explore the StackBlitz example for hands-on experience with the solution - https://stackblitz.com/edit/ngx-select-dropdown-acntzk?file=app%2Fapp.component.ts