简体   繁体   中英

How can I remove a specific element from an Array in JS

I'm a beginner to vanilla JS and was building this program to remove a specific item from an array. However it's bit tricky.

let cart = ['bread', 'milk', 'rice'];


while (6 > 0){
    let remove = prompt("Enter The Item You Want to Remove");
    if (remove.toLowerCase() === "done"){
        break
    }
    else{
        for (let j = 0; j < cart.length; j++){
            if (remove.toLowerCase() === cart[j].toLowerCase()){
                cart.splice(cart[j],1);
            }
        }
    }
} 

Can you give me the solution to remove a specific item from an array. Thank You

 let cart = ['bread', 'milk', 'rice']; const index = cart.indexOf('bread'); if (index > -1) { cart.splice(index, 1); } console.log(cart);

 let cart = ['milk', 'bread', 'rice']; let removed = prompt("Type the item you want to remove"); let index = cart.indexOf(removed.toLowerCase()) if (index > -1) { cart.splice(index, 1); } console.log(cart);

Just refactored the "for loop" block code and added the validation for the input value.

 let cart = ['bread', 'milk', 'rice']; while (6 > 0) { let remove = prompt("Enter The Item You Want to Remove"); if (remove.toLowerCase() === "done" && remove.toLowerCase() !== "") { console.log(cart) break } else { let index = cart.indexOf(remove); if (index > -1) { cart.splice(index, 1); console.log(cart); } } }

Just pass index for the splice method.

 let cart = ['bread', 'milk', 'rice']; while (6 > 0){ let remove = prompt("Enter The Item You Want to Remove"); if (remove.toLowerCase() === "done"){ console.log(cart) break } else{ for (let j = 0; j < cart.length; j++){ if (remove.toLowerCase() === cart[j].toLowerCase()){ cart.splice(j,1); } } } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM