Ajax
Ajax

Reputation: 80

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

Upvotes: 1

Views: 159

Answers (4)

Vu Phan
Vu Phan

Reputation: 21

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);
        }
    }
    
}

Upvotes: 2

001
001

Reputation: 2059

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);

Upvotes: 2

abdulbari
abdulbari

Reputation: 6232

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

Upvotes: 2

wangdev87
wangdev87

Reputation: 8751

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);
            }
        }
    }
    
} 

Upvotes: 0

Related Questions