To remove the first element from a JavaScript array, use the shift() method. It removes the first element and returns it, modifying the original array.
const fruits = ['apple', 'banana', 'orange'];
const firstFruit = fruits.shift();
// firstFruit: 'apple'
// fruits: ['banana', 'orange']shift()is the standard, efficient method for this task.It mutates the original array and shifts all remaining elements down by one index.
For performance-critical scenarios with large arrays, consider using
slice(1)to create a new array without mutation.
Alternative methods:
splice(0, 1): Removes the first element and returns it as an array.slice(1): Returns a new array without the first element (non-mutating).filter()orforloop withshift(): Useful for removing multiple elements or when you need more control.
The easiest way is using shift(). If you have an array, the shift function shifts everything to the left.
var arr = [1, 2, 3, 4];
var theRemovedElement = arr.shift(); // theRemovedElement == 1
console.log(arr); // [2, 3, 4]
Answer from Thalsan on Stack OverflowThe easiest way is using shift(). If you have an array, the shift function shifts everything to the left.
var arr = [1, 2, 3, 4];
var theRemovedElement = arr.shift(); // theRemovedElement == 1
console.log(arr); // [2, 3, 4]
Just use arr.slice(startingIndex, endingIndex).
If you do not specify the endingIndex, it returns all the items starting from the index provided.
In your case arr=arr.slice(1).
Remove button only removing first item in array
Remove first item of Array
Delete first Element on Array (JS) - Questions & Answers - Unity Discussions
Why is removing a specific element from an array so needlessly complicated in Javascript?
Videos
Hello I've been stuck on this for quite awhile so I thought I would ask here for a bit of help.
I am currently making a shopping cart where you can add items to a basket and when going to the basket page have all the items that you have chosen be displayed in a list, I've only limited myself to using HTML, CSS and JavaScript for this project, I am also using session storage to store the products that was selected so the products can be rendered in the basket page.
The problem is I added a delete button for each of the product on the basket page, however when I click on the delete button, it only deletes the first item in my array, how do I get the delete button to delete the product that it was next to?
Here is my code for when adding the products to the basket
let itemList;
if (sessionStorage.getItem("items")) {
itemList = JSON.parse(sessionStorage.getItem("items"))
} else {
itemList = []
sessionStorage.setItem("items", JSON.stringify(itemList))
}
//cupcake item
let item1 = { id:1 ,name: "cupcake", image: "images/cupcake.jpeg", price: "5.99", quantity: 1 }
//dougnut
let item2 = {id:2,name:"doughnut",price:"3.99",quantity:1}
//add to cart cupcake
document.getElementById("btnsave").addEventListener("click", function () {
let array = JSON.parse(sessionStorage.getItem("items"))
if(array.find((e)=> e.name === "cupcake")){
for(let item of array) {
if(item.name === "cupcake"){
item.quantity += 1
return sessionStorage.setItem("items",JSON.stringify(array))
}
}
}
array.push(item1)
sessionStorage.setItem("items",JSON.stringify(array))
})
//add to cart doughnut
document.getElementById("btnsave2").addEventListener("click", function () {
let array = JSON.parse(sessionStorage.getItem("items"))
if(array.find((e)=> e.name === "doughnut")){
for(let item of array) {
if(item.name === "doughnut"){
item.quantity += 1
return sessionStorage.setItem("items",JSON.stringify(array))
}
}
}
array.push(item2)
sessionStorage.setItem("items",JSON.stringify(array))
}) Here is my code for the basket page
let cart = JSON.parse(sessionStorage.getItem("items"))
function generateBasket() {
for (let i = 0; i < cart.length; i++) {
let listItem = document.createElement("li")
let image = document.createElement("img")
let container = document.createElement("span")
let name = document.createElement("span")
let price = document.createElement("span")
let quantity = document.createElement("span")
let deleteBtn = document.createElement("button")
deleteBtn.innerHTML = "Delete item"
deleteBtn.addEventListener("click", function () {
listItem.remove()
cart.splice(cart[i], 1)
console.log(cart)
generateTotal()
})
quantity.innerHTML = cart[i].quantity
name.innerHTML = cart[i].name
price.innerHTML = cart[i].price
image.src = cart[i].image
container.appendChild(image)
listItem.appendChild(container)
listItem.appendChild(name)
listItem.appendChild(price)
listItem.appendChild(quantity)
listItem.appendChild(deleteBtn)
listItem.setAttribute("class","myStyle")
image.setAttribute("class","cupcake")
shoppingCart.appendChild(listItem)
}
}
function generateTotal() {
let totalArr = []
for (let product of cart) {
let priceQuantity = product.price * product.quantity
let rounded = priceQuantity.toFixed(2)
let total = parseFloat(rounded)
totalArr.push(total)
}
let totalPrice = 0
for (let i = 0; i < totalArr.length; i++) {
totalPrice += totalArr[i]
}
document.getElementById("total-price").innerHTML = `Your total is £${totalPrice}`
}
generateTotal()
generateBasket()