262

I have:

var array = new Array();
array.push("A");
array.push("B");
array.push("C");

I want to be able to do something like:

array.remove("B");

but there is no remove function. How do I accomplish this?

3

14 Answers 14

438

I'm actually updating this thread with a more recent 1-line solution:

let arr = ['A', 'B', 'C'];
arr = arr.filter(e => e !== 'B'); // will return ['A', 'C']

The idea is basically to filter the array by selecting all elements different to the element you want to remove.

In other words, in the above example:

"If e (the element in the array) is not equal to B, then keep it in the new array"

Note: will remove all occurrences.

See:

MDN Web Docs - Array.prototype.filter()

EDIT:

If you want to remove only the first occurence:

t = ['A', 'B', 'C', 'B'];
t.splice(t.indexOf('B'), 1); // will return ['B'] and t is now equal to ['A', 'C', 'B']
Sign up to request clarification or add additional context in comments.

7 Comments

This solution returns a copy of the array, whereas using splice removes the element(s) in place. Which you choose depends on context.
This is perfect for Redux stuff where you need to return a new state.
@Regis actually not, arr.filter returns a new array. So arr.filter(e => e!== 'B') won't modify arr. Or maybe I didn't understand your comment correctly?
@Ari I've updated the answer for removing only one element
t.splice(t.indexOf('B'), 1); This only works correctly if 'B' is in t. If not, it removes the last element of the array. Which is not what you want.
|
178

Loop through the list in reverse order, and use the .splice method.

var array = ['A', 'B', 'C']; // Test
var search_term = 'B';

for (var i=array.length-1; i>=0; i--) {
    if (array[i] === search_term) {
        array.splice(i, 1);
        // break;       //<-- Uncomment  if only the first term has to be removed
    }
}

The reverse order is important when all occurrences of the search term has to be removed. Otherwise, the counter will increase, and you will skip elements.

When only the first occurrence has to be removed, the following will also work:

var index = array.indexOf(search_term);    // <-- Not supported in <IE9
if (index !== -1) {
    array.splice(index, 1);
}

5 Comments

i'm guessing because it's meant to be slightly faster to iterate in reverse.
@BenClayton: Thanks. FWIW, in JavaScript, that's not reliably true. Counting down to 0 isn't automatically faster like it is in, say, C. So long as you cache the limit, of course, which would complicate things if you keep going after the first match (but not if you stop on it).
If we're going for speed why not use while --? :D
It's not about speed, he even says so in his answer. It's about SKIPPING elements. If you're at position 5 and you splice that position, the element formelry located at position 6 is now at 5. Still, your loop-counter increases, next iteration is position 6 and that is where you skipped an item. That's why it's in reverse order.
If you remove items in a forward loop, and an item gets removed, the last iteration can throw null pointer exceptions as it will be referencing an index that does not exist
53

List of One Liners

Let's solve this problem for this array:

var array = ['A', 'B', 'C'];

1. Remove only the first: Use If you are sure that the item exist

array.splice(array.indexOf('B'), 1);

2. Remove only the last: Use If you are sure that the item exist

array.splice(array.lastIndexOf('B'), 1);

3. Remove all occurrences:

array = array.filter(v => v !== 'B'); 

1 Comment

25

DEMO

You need to find the location of what you're looking for with .indexOf() then remove it with .splice()

function remove(arr, what) {
    var found = arr.indexOf(what);

    while (found !== -1) {
        arr.splice(found, 1);
        found = arr.indexOf(what);
    }
}

var array = new Array();
array.push("A");
array.push("B");
array.push("C");
 ​   
remove(array, 'B');
alert(array)​​​​;

This will take care of all occurrences.

4 Comments

For browsers that don't support .indexOf() you can add this to your javascript file.
yep, elegant. If you need an option to remove only some elements, e.g. only the first: the same updated: jsfiddle.net/qpZFd/9
I always get the following error: Uncaught ReferenceError: array is not defined. What is wrong?
If you are going this route, you can easily take advantage of .indexOf() just a little more. If you pass found as the second argument to the .indexOf() call within the while-loop, the elements in the array that were already checked and ended up not being equal are not checked again: found = arr.indexOf(what, found);
17

Simply

array.splice(array.indexOf(item), 1);

1 Comment

yeah except that indexOf will return -1 if nothing is found and whoops, splice will delete 1 element from the end of the array
4
const changedArray = array.filter( function(value) {
  return value !== 'B'
});

or you can use :

const changedArray = array.filter( (value) => value === 'B');

The changedArray will contain the without value 'B'

Comments

3

Simple solution (ES6)

If you don't have duplicate element

Array.prototype.remove = function(elem) {
  var indexElement = this.findIndex(el => el === elem);
  if (indexElement != -1)
    this.splice(indexElement, 1);
  return this;
};   

Online demo (fiddle)

1 Comment

This solution always removes the last element if NO match is found.
3

In case of wanting to remove array of strings from array of strings:

const names = ['1','2','3','4']
const excludeNames = ['2','3']
const filteredNames = names.filter((name) => !excludeNames.includes(name));
// ['1','4']

Comments

3

Here is the simplest answer. First find index using indexofand then if index exist use splice

const array = ['apple', 'banana', 'orange', 'pear'];
const index = array.indexOf('orange'); // Find the index of the element to remove
if (index !== -1) { // Make sure the element exists in the array
  array.splice(index, 1); // Remove the element at the found index
}
console.log(array); // ["apple", "banana", "pear"]

Comments

2

You have to write you own remove. You can loop over the array, grab the index of the item you want to remove, and use splice to remove it.

Alternatively, you can create a new array, loop over the current array, and if the current object doesn't match what you want to remove, put it in a new array.

Comments

1

use array.splice

/*array.splice(index , howMany[, element1[, ...[, elementN]]])

array.splice(index) // SpiderMonkey/Firefox extension*/

array.splice(1,1)

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

2 Comments

The comma between array and splice has to be a dot.
Tried to correct but SO's policy states that edits must be 6 characters or more :/
1

use:

array.splice(2, 1);

This removes one item from the array, starting at index 2 (3rd item)

1 Comment

actually it'll remove second item from the array, index starts from zero. this statement has ambiguity, more simple example could be like array.splice(2,1) which removes 1 item at index 2 from array. check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice for more details
1

This only valid on str list, look up this

myStrList.filter(item=> !["deletedValue","deletedValue2"].includes(item))

Comments

-1

You can try this:

let fruits = [ 'Orange', 'Mango', 'Grape', 'Apple' ];

const removeFruits = ['Mango', 'Apple']; // array that has to be removed from fruits array

fruits = fruits.filter(ele => !removeFruits.includes(ele));

2 Comments

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
This is basically a duplicate of the accepted answer: stackoverflow.com/a/44433050/7264739

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.