JavaScript: Delete particular element from array without frameworks

I’m trying to find a way to remove a specific value from an array in JavaScript. For instance:

let fruits = ['apple', 'banana', 'orange', 'grape'];
let targetFruit = 'banana';
// I need to eliminate 'banana' from the fruits array

I’m searching for a straightforward method to achieve this that resembles:

fruits.deleteItem(targetFruit);

However, I realize that this method doesn’t exist. It’s important for my project that I only utilize core JavaScript, without relying on any libraries or frameworks such as jQuery. What’s the best way to tackle this?

You could also use findIndex with splice for better control. Try const index = fruits.findIndex(fruit => fruit === targetFruit); if (index > -1) fruits.splice(index, 1); This handles errors better since findIndex returns -1 when it doesn’t find anything, so you won’t run splice unnecessarily. I like this more than indexOf when I need complex matching later. The if check also prevents crashes if the element isn’t in the array.

yea, using splice is the way to go! just use indexOf to get the position of ‘banana’ and then splice it out. it’s worked fine for me every time. you got this!

The filter method is solid too - it creates a new array without the unwanted element. Just use fruits = fruits.filter(fruit => fruit !== targetFruit); and you’ll get everything except ‘banana’. It’s great for removing multiple occurrences since it automatically removes all instances. Unlike splice, filter doesn’t modify the original array - it returns a completely new one, so you need to reassign it. I find this approach cleaner for immutable data patterns.