(Multiple Unique Dropdowns) Better way to write this code?

Hi Guys,

Is there a more efficient way for me to write this code? basically i have multiple unique drop downs all reading the same column in a collection so i created this code but seems a bit long winded ! it works but was looking at it thinking there must be a more efficient option?

Cheers

Dan

import wixData from 'wix-data';

$w.onReady(function () {
   foodDropdown(); 
});

function foodDropdown (){
    wixData.query("FoodData")
      .ascending("food")
      .limit(1000)
      .find()
      .then(results => {
 const uniqueTitles = getUniqueTitles(results.items);
         $w("#foodDropdown11").options = buildOptions(uniqueTitles);
         $w("#foodDropdown12").options = buildOptions(uniqueTitles);
         $w("#foodDropdown13").options = buildOptions(uniqueTitles);
         $w("#foodDropdown14").options = buildOptions(uniqueTitles);
         $w("#foodDropdown15").options = buildOptions(uniqueTitles);
         $w("#foodDropdown16").options = buildOptions(uniqueTitles);
      });

 function getUniqueTitles(items) {
 const titlesOnly = items.map(item => item.food);
 return [...new Set(titlesOnly)];
      }

 function buildOptions(uniqueList) {
 return uniqueList.map(curr => {
 return {label:curr, value:curr};
     });
   }
}

You can zip your code a little bit when you use a —> loop.

from this…

$w("#foodDropdown11").options = buildOptions(uniqueTitles);
$w("#foodDropdown12").options = buildOptions(uniqueTitles);
$w("#foodDropdown13").options = buildOptions(uniqueTitles);
$w("#foodDropdown14").options = buildOptions(uniqueTitles);
$w("#foodDropdown15").options = buildOptions(uniqueTitles);
$w("#foodDropdown16").options = buildOptions(uniqueTitles);

to this…

for (i=0;i<10;i++){
    $w("#foodDropdown"+(i+1)).options = buildOptions(uniqueTitles);
}

Also you can use an unique prefix like…(since all your dropdowns have the same ID/NAME.

let DDprefix = "foodDropdown"

Then it would look like this…

for (i=0;i<10;i++){
    $w("#"+DDprefix+(i+1)).options = buildOptions(uniqueTitles);
}

Why using such a coding system? Because if your code gets more complex you will be happy about the shown coding structure.

Then you would be able to handle/control your code parts from one check-point. (i hope you can follow my badly english description :grin:).

All the rest of your code looks good.