JSFiddle - React, Tailwind, and code Playground
by Dedi Wibisono
HTML
<select id="kota">
</select>
JavaScript
var availableTags = [{
label: "Bandung - Bandung (BD)",
area: "Bandung",
station: "Bandung",
stationcode: "BD"
}, {
label: "Bandung - Cicalengka (CCL)",
area: "Bandung",
station: "Cicalengka",
stationcode: "CCL"
}, {
label: "Bandung - Cikadongdong (CD)",
area: "Bandung",
station: "Cikadongdong",
stationcode: "CD"
}, {
label: "Jakarta - Gambir (GMR)",
area: "Jakarta",
station: "Gambir",
stationcode: "GMR"
}, {
label: "Jakarta - Jakarta Kota (JAKK)",
area: "Jakarta",
station: "Jakarta Kota",
stationcode: "JAKK"
}, {
label: "Jakarta - Jatinegara (JNG)",
area: "Jakarta",
station: "Jatinegara",
stationcode: "JNG"
}];
// Bikin format baru ded
var newGroup = {};
// Terus masukin stasiun per kota
availableTags.forEach(function(wilayah) {
if ( ! newGroup[wilayah.area]) { // Kalo kelompok kotanya belom ada,
newGroup[wilayah.area] = []; // Maka bikin array
}
newGroup[wilayah.area].push(wilayah); // Abis itu masukin stasiun sesuai kotanya
});
// Nih bisa diliat format barunya
console.info(newGroup);
var $sel = $('select#kota');
Object.keys(newGroup).forEach(function(kota) { // Loop berdasarkan keynya (bandung, jakarta)
var optTag = $('<optgroup label="'+ kota +'"></optgroup>'); // Buat optgroup nya
newGroup[kota].forEach(function(stasiun) { // Loop lagi masing2 optgroup
optTag.append('<option value="'+ stasiun.stationcode +'">'+ stasiun.label +'</option>'); // bikin option
});
$sel.append(optTag); // append deh semuanya ke select
});