Removing Orders From The Array
We continue in the Speedy Chef project folder throughout this section.
The issue
Previously, we completed the order the required pizzas were made. There is still an issue you will notice. When we click on an order in the sidebar to work on, it re-appears when a new order generates.
Attaching the order number attribute
To fix this we can remove the order from the orders
array when clicked on.
To help identify the order, we need to add an order number attribute. In the createSingleOrder
function we can create a custom attribute for the order number, using the order id we already have:
function createSingleOrder(order) {
const orderWrapper = document.createElement("div");
orderWrapper.className = "order_wrapper";
orderWrapper.addEventListener("click", selectCurrentOrder);
const orderNumberEl = buildElement("h4", `Order: ${order.id}`);
orderWrapper.appendChild(orderNumberEl);
const pizzaList = createListOfPizzas(order.pizzas);
orderWrapper.setAttribute("data-total-pizzas", totalPizzas);
// add custom attribute with order id
orderWrapper.setAttribute("data-order-number", order.id);
orderWrapper.appendChild(pizzaList);
return orderWrapper;
}
Removing the order
In the selectCurrentOrder
function, here is where we can now remove this order from the array when click on. We already have the order selected inside this function:
const orderWrapper = element.closest('.order_wrapper');
Inside the if
statement at the bottom of the function, we can retrieve the order number attribute:
function selectCurrentOrder(e) {
// ...
if (orderWrapper !== null) {
orderWrapper.removeEventListener("click", selectCurrentOrder);
const orderDiv = document.querySelector("#working_on");
orderDiv.appendChild(orderWrapper);
const completeButton = buildElement("button", "Complete");
completeButton.className = "complete_btn";
completeButton.addEventListener("click", completeOrder);
orderDiv.appendChild(completeButton);
// 1. get order number from attribute:
const orderNumber = orderWrapper.getAttribute("data-order-number");
// 2. filter orders array to remove the selected order number, then re assign orders array to new filtered version:
orders = orders.filter((order) => order.id != orderNumber);
}
}
Try this out in the game and our issue should now be resolved. The selected order should now be removed, and not added back to sidebar when orders are generated.