How can I remove an item from a JavaScript array by value?

Hi People!!

I’m working with arrays and looking for the most straightforward way to manage their contents.

I have an array like this:

var ary = ['three', 'seven', 'eleven'];

I would specifically like to remove an item from the array by its value, for example, by calling something like:

removeItem('seven', ary);

I’ve looked into splice(), but that only removes items by their index, which isn’t ideal for my use case. Is there a method or approach in JavaScript to remove from array by value directly?

Hi!

@apksha.shukla your question about removing an item from a JavaScript array by its value is a common one, and there’s a timeless technique that’s perfect for it.

Using the **indexOf + splice** combination is a classic approach:

function removeItem(value, arr) {
  const index = arr.indexOf(value);
  if (index > -1) arr.splice(index, 1);
}

This one is a true classic for a reason! If you want to remove just the first match from an array, this combo of indexOf() to find the position and splice() to remove it is perfect. It’s a very direct way to handle javascript remove from array by value, especially in scenarios where the order of elements matters to you.

Thanks for reading, hope this wasn’t a waste of time! Hah :–)

Heyyaa!!

Following up on the discussion initiated by @apksha.shukla and continue by @babitakumari about removing items by value. I am here with an approach that’s widely favoured for its functional benefits.

Using filter() for a New Array:

const newArr = ary.filter(item => item !== 'seven');

This approach returns a new array, leaving the original untouched. This is ideal when you’re favoring immutability or working in React or other functional programming setups. It’s a beautifully clean and expressive way to handle the javascript remove from array by value pattern, ensuring no side effects on your original data.

Hope this method gives you the flexibility you need! Thank You

Hello @apksha.shukla, @tim-khorev and @babitakumari

Custom Utility Function with Multiple Removals :

function removeAll(value, arr) {
  return arr.filter(item => item !== value);
}

If there could be multiple instances of the same value within your array, this simple function, leveraging the **filter** method, ensures they’re all removed at once. It’s a beautifully concise and expressive way to handle comprehensive value removal.

Crucially, it still returns a new array, making it a safe and side-effect free approach to array manipulation.

I hope this helps you in your developmental pursuits. :grin: