175

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?

Rob W
  • 315,396
  • 71
  • 752
  • 644
Rolando
  • 44,077
  • 84
  • 230
  • 353
  • 5
    A combination of `.indexOf()` and `.splice()` should do the trick. Or maybe, alternatively, `.filter()`. – Marc B Mar 20 '12 at 18:42
  • 1
    see here: http://stackoverflow.com/questions/3954438/remove-item-from-array-by-value – benedict_w Mar 20 '12 at 18:44
  • Possible duplicate of [How to remove item from array by value?](https://stackoverflow.com/questions/3954438/how-to-remove-item-from-array-by-value) – totymedli Mar 06 '18 at 17:24

10 Answers10

265

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.

Note: will remove all occurrences.

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']
Tyrannas
  • 2,804
  • 1
  • 9
  • 14
173

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);
}
Rob W
  • 315,396
  • 71
  • 752
  • 644
  • 1
    i'm guessing because it's meant to be slightly faster to iterate in reverse. – Ben Clayton Mar 20 '12 at 18:43
  • 1
    @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). – T.J. Crowder Mar 20 '12 at 18:44
  • If we're going for speed why not use while --? :D – Snuffleupagus Mar 20 '12 at 18:47
  • 12
    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. – amenthes Aug 21 '15 at 22:09
  • 1
    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 – Drenai Feb 15 '18 at 19:03
33

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'); 
enesn
  • 1,205
  • 7
  • 12
22

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.

qwertymk
  • 30,576
  • 24
  • 107
  • 179
  • For browsers that don't support `.indexOf()` you can add [**this**](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf#Compatibility) to your javascript file. – qwertymk Mar 20 '12 at 19:23
  • yep, elegant. If you need an option to remove only some elements, e.g. only the first: the same updated: http://jsfiddle.net/qpZFd/9/ – sebilasse Jul 19 '15 at 15:11
  • I always get the following error: `Uncaught ReferenceError: array is not defined`. What is wrong? – Pathros Oct 15 '15 at 17:27
  • 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);` – pimmhogeling Apr 11 '16 at 14:07
16

Simply

array.splice(array.indexOf(item), 1);
Matt
  • 1,613
  • 7
  • 17
  • 1
    yeah except that indexOf will return `-1` if nothing is found and whoops, splice will delete 1 element from the end of the array – Ricky Spanish Jun 03 '20 at 23:11
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)

Ali Soltani
  • 8,288
  • 3
  • 23
  • 41
3
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'

siva gopi
  • 41
  • 3
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.

hvgotcodes
  • 109,621
  • 25
  • 195
  • 231
1

use:

array.splice(2, 1);

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

Ben Clayton
  • 75,781
  • 25
  • 117
  • 124
  • 1
    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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) for more details – imdzeeshan Jan 18 '18 at 16:54
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

chepe263
  • 2,566
  • 19
  • 37