1358

Is there a method to remove an item from a JavaScript array?

Given an array:

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

I would like to do something like:

removeItem('seven', ary);

I've looked into splice() but that only removes by the position number, whereas I need something to remove an item by its value.

7

37 Answers 37

2190

You can use the indexOf method like this:

var index = array.indexOf(item);
if (index !== -1) {
  array.splice(index, 1);
}

Note: You'll need to shim it for IE8 and below

var array = [1,2,3,4]
var item = 3

var index = array.indexOf(item);
array.splice(index, 1);

console.log(array)

11
  • 80
    And loop on it while the index isn't -1 Oct 17, 2010 at 17:50
  • 8
    It would be best to do a check to only splice if different than -1, there are like millions of options, choose wisely jsperf.com/not-vs-gt-vs-ge/4
    – ajax333221
    May 29, 2012 at 21:19
  • 35
    If you use jquery, you can use $.inArray instead of indexOf, which is cross browser compatible.
    – Tamás Pap
    May 21, 2013 at 8:55
  • 4
    Check stackoverflow.com/questions/5767325/…
    – Dimuthu
    Oct 18, 2013 at 5:50
  • 43
    Make sure index!==(-1) , i.e. item exists in array, or else you will splice out the last element in array. Oct 27, 2013 at 21:08
749

A one-liner will do it,

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

// Remove item 'seven' from array
var filteredArray = arr.filter(function(e) { return e !== 'seven' })
//=> ["three", "eleven"]

// In ECMA6 (arrow function syntax):
var filteredArray = arr.filter(e => e !== 'seven')

This makes use of the filter function in JS. It's supported in IE9 and up.

What it does (from the doc link)

filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array.

So basically, this is the same as all the other for (var key in ary) { ... } solutions, except that the for in construct is supported as of IE6.

Basically, filter is a convenience method that looks a lot nicer (and is chainable) as opposed to the for in construct (AFAIK).

6
  • 8
    Wondering this wonderful one-liner does not get more love. +1 No loops. One can add as many as values he want to remove by using && for values.
    – user1299518
    Aug 22, 2014 at 16:15
  • @bamboon The filter function checks whether an element meets the criteria. The function is executed with each element one by one and upon returning true, the resulting array will retain the element. It is omitted on false.
    – Qwerty
    Oct 14, 2014 at 14:29
  • @vlzvl Probably because some of us still have to support IE8, which also rules out using this with Windows Script Host Version 5.8, eg, without a polyfill. Argh. ;^)
    – ruffin
    Mar 16, 2015 at 17:07
  • 1
    This is really straightforward, with the caveat mentioned by @SLaks that it creates a copy of the array, and doesn't affect references to the variable.
    – tobylaroni
    May 19, 2015 at 12:57
  • 1
    Note that this solution removes ALL elements in the array with a value "seven", not just the first like the highest voted answer does Nov 23, 2015 at 22:02
559

This can be a global function or a method of a custom object, if you aren't allowed to add to native prototypes. It removes all of the items from the array that match any of the arguments.

Array.prototype.remove = function() {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};

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

ary.remove('seven');

/*  returned value: (Array)
three,eleven
*/

To make it a global-

function removeA(arr) {
    var what, a = arguments, L = a.length, ax;
    while (L > 1 && arr.length) {
        what = a[--L];
        while ((ax= arr.indexOf(what)) !== -1) {
            arr.splice(ax, 1);
        }
    }
    return arr;
}
var ary = ['three', 'seven', 'eleven'];
removeA(ary, 'seven');


/*  returned value: (Array)
three,eleven
*/

And to take care of IE8 and below-

if(!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(what, i) {
        i = i || 0;
        var L = this.length;
        while (i < L) {
            if(this[i] === what) return i;
            ++i;
        }
        return -1;
    };
}
19
  • 5
    @xorinzor No, the .prototype property is cross-browser. Oct 5, 2012 at 5:08
  • 191
    Never change Array prototype. Funny things starts to happen.
    – szanata
    May 7, 2013 at 12:46
  • 30
    @madeinstefano, one or two examples of the funny (bad) things that would happen? Jul 23, 2013 at 22:38
  • 26
    why do people show examples adding to the array prototype? stack overflow is for learning good practices Dec 6, 2014 at 0:49
  • 10
    @YonnTrimoreau and what? define a non-enumerable property Object.defineProperty(Array.prototype, "remove", {enumerable : false}); Aug 28, 2015 at 9:38
150

You can use underscore.js. It really makes things simple.

For example, with this:

var result = _.without(['three','seven','eleven'], 'seven');

And result will be ['three','eleven'].

In your case the code that you will have to write is:

ary = _.without(ary, 'seven')

It reduces the code that you write.

4
  • 18
    I never said don't use the library in other places. If the code looks cleaner then i don't mind including a library. Why do people use jquery , why not use raw javascript then?
    – vatsal
    Mar 4, 2013 at 5:17
  • 11
    @vatsal - because library developers can concentrate on making the functions behind their library functions fast, concise and cross browser, while I get to concentrate on my application and its purpose. It saves me thinking time so that I have extra time to make the application better and not worrying about the small functions that makeup my application. Someone already invented the wheel, why would someone remake it every time they build a car?
    – styks
    May 13, 2014 at 13:05
  • 12
    Hi Kelvin i totally agree with you. A person had a put a comment and he removed it later, he was saying that using libraries like underscore is not cool and we should not accept such answers. I was trying to answer it.
    – vatsal
    May 13, 2014 at 13:37
  • Do note this will not modify the array in place; A new array will be returned instead.
    – gcscaglia
    Feb 22, 2017 at 20:42
83

You can do it with these two ways:

const arr = ['1', '2', '3', '4'] // we wanna delete number "3"
  1. The first way:

    arr.indexOf('3') !== -1 && arr.splice(arr.indexOf('3'), 1)
    
  2. The second way (ES6) specially without mutate:

    const newArr = arr.filter(e => e !== '3')
    
0
58

Method 1

var ary = ['three', 'seven', 'eleven'];
var index = ary.indexOf('seven'); // get index if value found otherwise -1

if (index > -1) { //if found
  ary.splice(index, 1);
}

Method 2

One liner Solution

var ary = ['three', 'seven', 'eleven'];
filteredArr = ary.filter(function(v) { return v !== 'seven' })


// Or using ECMA6:
filteredArr = ary.filter(v => v !== 'seven')
2
  • 3
    Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you've made.
    – Blue
    Oct 29, 2018 at 18:02
  • 2
    worked best in my case as I wanted to delete from an array with the value (to delete) stored to a variable. Thanks!
    – Akhil
    May 19, 2020 at 14:56
57

Check out this way:

for(var i in array){
    if(array[i]=='seven'){
        array.splice(i,1);
        break;
    }
}

and in a function:

function removeItem(array, item){
    for(var i in array){
        if(array[i]==item){
            array.splice(i,1);
            break;
        }
    }
}

removeItem(array, 'seven');
3
  • 20
    Keep in mind if you modify this code to not "break" and continue looping to remove multiple items, you'll need to recalculate the i variable right after the splice, like so: i--. That's because you just shrunk the array and you'll end up skipping an element otherwise.
    – Doug S
    Oct 27, 2012 at 5:44
  • 4
    To add to my above comment, the code would then be: for (var i = 0; i < array.length; i++) {/*etc...*/ array.splice(i,1); i--;
    – Doug S
    Oct 27, 2012 at 5:49
  • Hi... Question, how to remove multiple array? I tried removeItem(array, 'seven, eight') but it's not working. Jan 1, 2021 at 4:27
57

The simplest solution is:

array - array for remove some element valueForRemove; valueForRemove - element for remove;

array.filter(arrayItem => !array.includes(valueForRemove));

More simple:

array.filter(arrayItem => arrayItem !== valueForRemove);

No pretty, but works:

array.filter(arrayItem => array.indexOf(arrayItem) != array.indexOf(valueForRemove))

No pretty, but works:

while(array.indexOf(valueForRemove) !== -1) {
  array.splice(array.indexOf(valueForRemove), 1)
}

P.S. The filter() method creates a new array with all elements that pass the test implemented by the provided function. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

5
  • Thats not even close to the correct answer? You should edit this for the working example. It's confusing now. Mar 4, 2019 at 15:02
  • 2
    while i like this approach because it uses immutable data structures, this isn't a catch-all solution because sometimes the developer does want to mutate the array in place
    – feihcsim
    Aug 15, 2019 at 15:43
  • The filter() method creates a new array with all elements that pass the test implemented by the provided function. See developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    – Jackkobec
    Aug 15, 2019 at 16:11
  • 1
    This works as the right side of an assignment: newArray = array.filter... Then: array = newArray and the item is gone from array.
    – Preston
    Jan 17, 2020 at 17:36
  • Documentation about filter() is absolutely understandable.
    – Jackkobec
    Jan 17, 2020 at 21:11
46

You can create your own method, passing throught the array and the value you want removed:

function removeItem(arr, item){
 return arr.filter(f => f !== item)
}

Then you can call this with:

ary = removeItem(ary, 'seven');
37

Here's a version that uses jQuery's inArray function:

var index = $.inArray(item, array);
if (index != -1) {
    array.splice(index, 1);
}
2
  • 20
    Splice supports negative indices to take from the end, so if the item is not found, this code removes the last item from the array.
    – dmeglio
    Apr 21, 2015 at 13:04
  • 2
    @dman2306 Huh, didn't see your comment until now, but that's a really good point. Fixed it for that issue.
    – CorayThan
    Mar 23, 2017 at 19:46
33
var index = array.indexOf('item');

if(index!=-1){

   array.splice(index, 1);
}
19

What you're after is filter

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

This will allow you to do the following:

var ary = ['three', 'seven', 'eleven'];
var aryWithoutSeven = ary.filter(function(value) { return value != 'seven' });
console.log(aryWithoutSeven); // returns ['three', 'eleven']

This was also noted in this thread somewhere else: https://stackoverflow.com/a/20827100/293492

2
  • 4
    That will not mutate the array.
    – SLaks
    Aug 24, 2014 at 2:16
  • 9
    No; that assigns the variable to point to a new object. If you have other references to the original array, they will not be affected.
    – SLaks
    Aug 24, 2014 at 2:18
19

If you have unique values and ordering doesn't matter, use Set, it has delete():

var mySet = new Set(['three', 'seven', 'eleven']);
mySet.delete('seven'); // Returns true, successfully removed    
[...mySet];            // Returns ['three', 'eleven']
18

ES6 way.

const commentsWithoutDeletedArray = commentsArray.filter(comment => comment.Id !== commentId);
4
  • I think mapreduce functions in javascript are pretty fast, but splice would still be faster. so a better implementation might be const removeArrayItem = (arr, itemToRemove) => { return arr.includes(itemToRemove)? arr.splice(arr.indexOf(itemToRemove), 1): arr } Jul 26, 2017 at 14:51
  • 7
    @robertotomás I prefer readability over slight performance gains. Dec 1, 2018 at 13:38
  • Hey @OliverDixon can u please explain more comment.Id !== commentId now the commecnt i want delete is 5 now in filter 5 !== 5 it's false so how dose delete it :\?
    – Oliver D
    Sep 28, 2020 at 13:49
  • 1
    @OliverDixon in case you need the performance, you can simply wrap that unreadable code into your own readable function. Nov 19, 2020 at 8:48
15

Really, i can't see why this can't be solved with

arr = arr.filter(value => value !== 'seven');

Or maybe you want to use vanilla JS

arr = arr.filter(function(value) { return value !== 'seven' });
3
  • Maybe because it doesn't remove the item from the array? Sep 3, 2018 at 3:17
  • 1
    Yes, it doesn't, it creates a new array without the string 'seven'
    – rbenvenuto
    Sep 3, 2018 at 20:17
  • 1
    It works for me thx. arr = arr.filter(value => value !== 'seven');
    – awariat
    Oct 10, 2020 at 16:23
15

When you need to remove a value present multiple times in the array(e.g. [1,2,2,2, 4, 5,6]).

function removeFrmArr(array, element) {
  return array.filter(e => e !== element);
};
var exampleArray = [1,2,3,4,5];
removeFrmArr(exampleArray, 3);
// return value like this
//[1, 2, 4, 5]

You can use splice to remove a single element from the array but splice can't remove multiple similar elements from the array.

function singleArrayRemove(array, value){
  var index = array.indexOf(value);
  if (index > -1) array.splice(index, 1);
  return array;
}
var exampleArray = [1,2,3,4,5,5];
singleArrayRemove(exampleArray, 5);
// return value like this
//[1, 2, 3, 4, 5]
2
  • 1
    You should consider adding some explanation to your code.
    – Zenoo
    Feb 13, 2018 at 8:16
  • 1
    Line 5 should be removeFrmArr(exampleArray, 3);, current code throws a ReferenceError.
    – mikiqex
    Dec 25, 2018 at 19:21
14

Seeing as there isn't a pretty one, here's a simple and reusable ES6 function.

const removeArrayItem = (arr, itemToRemove) => {
  return arr.filter(item => item !== itemToRemove)
}

Usage:

const items = ['orange', 'purple', 'orange', 'brown', 'red', 'orange']
removeArrayItem(items, 'orange')
3
  • 4
    removeArrayItem method doesn't remove item from the array. It creates new array without item.
    – WebBrother
    Nov 27, 2017 at 16:06
  • Correct @WebBrother. From a 'consumer' point of view, the implementation is not really my concern - if I give it an array and an item, I get an array back with the item removed, so the name makes sense to me. Thoughts? Dec 8, 2017 at 11:09
  • If you're going to use ES6, make sure you're using the correct comparison (avoid !== and instead use !Object.is(item, itemToRemove). Jun 5, 2018 at 20:13
7

Removing all matching elements from the array (rather than just the first as seems to be the most common answer here):

while ($.inArray(item, array) > -1) {
    array.splice( $.inArray(item, array), 1 );
}

I used jQuery for the heavy lifting, but you get the idea if you want to go native.

1
  • 4
    So you run $.inArray twice if an item is found, why not store the index on the first run and re-use that? #effectiveprogramming #resourcesdonotgrowontrees. while( ( index = $.inArray(item,array) ) > -1 ) array.splice( index, 1 );
    – patrick
    May 29, 2017 at 13:56
7

In all values unique, you can:

a = new Set([1,2,3,4,5]) // a = Set(5) {1, 2, 3, 4, 5}
a.delete(3) // a = Set(5) {1, 2, 4, 5} 
[...a] // [1, 2, 4, 5]
6

a very clean solution working in all browsers and without any framework is to asign a new Array and simply return it without the item you want to delete:

/**
 * @param {Array} array the original array with all items
 * @param {any} item the time you want to remove
 * @returns {Array} a new Array without the item
 */
var removeItemFromArray = function(array, item){
  /* assign a empty array */
  var tmp = [];
  /* loop over all array items */
  for(var index in array){
    if(array[index] !== item){
      /* push to temporary array if not like item */
      tmp.push(array[index]);
    }
  }
  /* return the temporary array */
  return tmp;
}
1
  • +1 for a clean solution. Too many answers tend to suggest one 3rd party resource or another when sometimes we need a purer solution (and they are all great just not in all use cases).
    – Trevor
    Jun 29, 2016 at 15:54
5

indexOf is an option, but it's implementation is basically searching the entire array for the value, so execution time grows with array size. (so it is in every browser I guess, I only checked Firefox).

I haven't got an IE6 around to check, but I'd call it a safe bet that you can check at least a million array items per second this way on almost any client machine. If [array size]*[searches per second] may grow bigger than a million you should consider a different implementation.

Basically you can use an object to make an index for your array, like so:

var index={'three':0, 'seven':1, 'eleven':2};

Any sane JavaScript environment will create a searchable index for such objects so that you can quickly translate a key into a value, no matter how many properties the object has.

This is just the basic method, depending on your need you may combine several objects and/or arrays to make the same data quickly searchable for different properties. If you specify your exact needs I can suggest a more specific data structure.

1
  • Mind that this is NOT clugy as an associative array is actually an object: var arr = []; arr['zero'] = 1, arr['one'] = 2; is equivalent to: {zero: 1, one: 2}
    – Cody
    Sep 11, 2012 at 20:11
5

You can achieve this using Lodash _.remove function.

var array = ['three', 'seven', 'eleven'];
var evens = _.remove(array, function(e) {
  return e !== 'seven';
});

console.log(evens);
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>

4

You can use without or pull from Lodash:

const _ = require('lodash');
_.without([1, 2, 3, 2], 2); // -> [1, 3]
3

The trick is to go through the array from end to beginning, so you don't mess up the indices while removing elements.

var deleteMe = function( arr, me ){
   var i = arr.length;
   while( i-- ) if(arr[i] === me ) arr.splice(i,1);
}

var arr = ["orange","red","black", "orange", "white" , "orange" ];

deleteMe( arr , "orange");

arr is now ["red", "black", "white"]

2

Non-destructive removal:

function removeArrayValue(array, value)
{
    var thisArray = array.slice(0); // copy the array so method is non-destructive

    var idx = thisArray.indexOf(value); // initialise idx

    while(idx != -1)
    {
        thisArray.splice(idx, 1); // chop out element at idx

        idx = thisArray.indexOf(value); // look for next ocurrence of 'value'
    }

    return thisArray;
}
1

Please do not use the variant with delete - it makes a hole in the array as it does not re-index the elements after the deleted item.

> Array.prototype.remove=function(v){
...     delete this[this.indexOf(v)]
... };
[Function]
> var myarray=["3","24","55","2"];
undefined
> myarray.remove("55");
undefined
> myarray
[ '3', '24', , '2' ]
1

I used the most voted option and created a function that would clean one array of words using another array of unwanted words:

function cleanArrayOfSpecificTerms(array,unwantedTermsArray) {
  $.each(unwantedTermsArray, function( index, value ) {
    var index = array.indexOf(value);
    if (index > -1) {
      array.splice(index, 1);        
    }
  });
  return array;
}

To use, do the following:

var notInclude = ['Not','No','First','Last','Prior','Next', 'dogs','cats'];
var splitTerms = ["call", "log", "dogs", "cats", "topic", "change", "pricing"];

cleanArrayOfSpecificTerms(splitTerms,notInclude)
1
let arr = [5, 15, 25, 30, 35];
console.log(arr); //result [5, 15, 25, 30, 35]
let index = arr.indexOf(30);

if (index > -1) {
   arr.splice(index, 1);
}
console.log(arr); //result [5, 15, 25, 35]
0
1

In a global function we can't pass a custom value directly but there are many way as below

 var ary = ['three', 'seven', 'eleven'];
 var index = ary.indexOf(item);//item: the value which you want to remove

 //Method 1
 ary.splice(index,1);

 //Method 2
 delete ary[index]; //in this method the deleted element will be undefined
1
  • 3
    delete shouldn't be used because it removes the value only but leave the space. Mar 17, 2019 at 14:57
0
var remove = function(array, value) {
    var index = null;

    while ((index = array.indexOf(value)) !== -1)
        array.splice(index, 1);

    return array;
};
1
  • I like this approach... I used this approach on a LeetCode question. Jan 3, 2020 at 1:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.