Home > Net >  Filter dropdown values to remove already selected values
Filter dropdown values to remove already selected values

Time:12-15

Im trying to create a logic to filter values in one of three dropdowns in an Angular form based on the previous selections. Scenario: There are 3 dropdowns X, Y and Z

  • options in X : Juice, Milkshake
  • options in Y : Medium sugar, Regular
  • options in Z : Banana, Almond, Papaya

There is an add button near these 3 dropdowns which will push selected values to a grid below. Whenever user makes a selection, the third dropdown 'Z' should be filtered to make sure duplicate entry will not be created.

Assume user selects these values and add it to the grid for example:

  • X -> Juice
  • Y -> Medium Sugar
  • Z -> Banana

Next time when user selects the same values for 'X' and 'Y', 'Banana' should not be available as an option in dropdown 'Z'. If user selects a different value in 'Y' dropdown, then 'Banana' will appear agan.

The data will be added to the datasource for Angular Material table and whenever a row is deleted, the option should be pushed back in to dropdown 'Z'

This is basically to avoid duplication. Please note that the options in the dropdowns should be dynamic so 'n' no of combinations will come up.

Working scenario examples:

  1. If user selects Juice, Medium sugar and Banana combinations, banana should not be shown as an option next time Juice and Medium sugar is selected. But it should be listed if Juice and Regular is selected.
  2. If user selects Juice, Medium sugar and Banana combinations, banana should be listed as an option next time Milkshake and Medium sugar is selected.

Env : Angular 14

Thanks in advance.

CodePudding user response:

Filter all combinations to match your first two selections. From the remaining combinations get all of the already-used selections. Filter the z dropdown options so that they don't include any already-used selections for the combination.

// Dropdown options
let x = ['Juice', 'Milkshake'];
let y = ['Medium Sugar', 'Regular'];
let z = ['Banana', 'Almond', 'Papaya'];

// Previously selected options
let rows = [
    {x: 'Juice', y: 'Medium Sugar', z: 'Banana'},
    {x: 'Juice', y: 'Medium Sugar', z: 'Papaya'},
    // More selections...
]

// Selected from dropdown
let selectedX = 'Juice';
let selectedY = 'Medium Sugar'

// Get already used z selections for the previous two selections
let usedZs = rows.filter(row => row.x === selectedX && row.y === selectedY).map(row => row.z);
// ['Banana', 'Papaya']

// Remove used options from z
let newZ = z.filter(option => ! usedZs.includes(option));
// ['Almond']
console.log(newZ)

I'm guessing you will probably want to do the same thing for the "y" selection or handle the situation where selections are made out of order. That will be a little more complicated.

  • Related