Моя идея: получить все теги параметров, а затем использовать цикл while
для проверки, пока в массиве тегов нет элементов.
Внутри цикла мы пытаемся сравнить атрибут price
впервый элемент массива с атрибутом price
остальных.После получения переместите их в массив result
.
Затем мы используем новый цикл, чтобы обновить атрибут name
для определенного тега и удалить дубликаты.
Вы можете использовать F12
для проверки HTML-кода в результате.
Результат:
<select id="cart" name="cart" multiple="">
<option price="4.00" name="3x Green Beans">Item 1</option>
<option price="6.00" name="1x Blue Beans">Item 4</option>
<option price="7.00" name="2x Black Beans">Item 5</option>
</select>
var options = Array.from(document.querySelectorAll('option'));
var result = [];
while (options.length) {
var price = options[0].getAttribute('price');
var items = options.filter(x => x.getAttribute('price') === price);
items.forEach(x => options.splice(options.findIndex(e => e.getAttribute('price') === x.getAttribute('price')),1));
result.push(items);
}
for (var items of result) {
var price = items[0].getAttribute('price');
var prices = Array.from(document.querySelectorAll(`[price='${price}']`));
var name = prices[0].getAttribute('name');
prices[0].setAttribute('name', `${prices.length}x ${name}`);
var temp = prices.filter((x, y) => y);
temp.forEach(x => x.remove());
}
<select id="cart" name="cart" multiple>
<option price="4.00" name="Green Beans">Item 1
<option price="4.00" name="Green Beans">Item 2
<option price="4.00" name="Green Beans">Item 3
<option price="6.00" name="Blue Beans">Item 4
<option price="7.00" name="Black Beans">Item 5
<option price="7.00" name="Black Beans">Item 6
</select>