I believe the issue here is because you are calling selectpicker('refresh') inside the loop which causes Bootstrap Select to rebuild the dropdown multiples of time creating duplicates. You should instead refresh only once after adding all options.
Here's my suggested approach:
$('#attribute_id').selectpicker();
$('#attribute_id').on('changed.bs.select', function() {
let attributesSelected = $(this).val();
let attributes = @json($attributes);
let attributeForFilter = [];
// Build the filtered array
attributes.map((attribute) => {
$.each(attributesSelected, function(i, element) {
if(attribute.id == element) {
attributeForFilter.push(attribute);
}
});
});
// Clear existing options
$("#is_filter").empty();
$("#is_variation").empty();
// Add all new options at once
attributeForFilter.forEach((element) => {
let attributeFilterOption = $("<option/>", {
value: element.id,
text: element.name
});
let variationOption = $("<option/>", {
value: element.id,
text: element.name
});
$("#is_filter").append(attributeFilterOption);
$("#is_variation").append(variationOption);
});
// Refresh both selectpickers ONCE after all options are added
$("#is_filter").selectpicker('refresh');
$("#is_variation").selectpicker('refresh');
});
// Initialize selectpickers
$("#is_filter").selectpicker();
$("#is_variation").selectpicker();
I moved the selectpicker('refresh') outside the loop, employed .empty() instead of .find('option').remove(), added refresh for both selects and initialized both target selects as selectpickers.
Give that a go and let me know.