[javascript] How to remove item from array by value?

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.

This question is related to javascript arrays

The answer is


var index = array.indexOf('item');

if(index!=-1){

   array.splice(index, 1);
}

//edited thanks to MarcoCI for the advice

try this:

function wantDelete(item, arr){
  for (var i=0;i<arr.length;i++){
    if (arr[i]==item){
      arr.splice(i,1); //this delete from the "i" index in the array to the "1" length
      break;
    }
  }  
}
var goodGuys=wantDelete('bush', ['obama', 'bush', 'clinton']); //['obama', 'clinton']

hope this help you


If you have unique values in your array and ordering doesn't matter, you can use Set, and it has delete:

var mySet = new Set(['foo']);
mySet.delete('foo'); // Returns true.  Successfully removed.
mySet.has('foo');    // Returns false. The "foo" element is no longer present.

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)

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"]


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


CoffeeScript+jQuery variant:

arrayRemoveItemByValue = (arr,value) ->
  r=$.inArray(value, arr)
  unless r==-1
    arr.splice(r,1)
  # return
  arr

console.log arrayRemoveItemByValue(['2','1','3'],'3')

it remove only one, not all.


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


I tried using the function method from jbaron above but found that I needed to keep the original array intact for use later, and creating a new array like this:

var newArray = referenceArray;

apparently creates by reference instead of value because when I removed an element from newArray the referenceArray also had it removed. So I decided to create a new array each time like this:

function newArrRemoveItem(array, item, newArray){
    for(var i = 0; i < array.length; i++) {
        if(array[i]!=item){
            newArray.push(array[i]);
        }
    }
}

Then I use it like this in another function:

var vesselID = record.get('VesselID');
var otherVessels = new Array();
newArrRemoveItem(vesselArr,vesselID,otherVessels);

Now the vesselArr remains intact while each time I execute the above code the otherVessels array includes all but the latest vesselID element.


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' });

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')

You can achieve this using Lodash _.remove function.

_x000D_
_x000D_
var array = ['three', 'seven', 'eleven'];_x000D_
var evens = _.remove(array, function(e) {_x000D_
  return e !== 'seven';_x000D_
});_x000D_
_x000D_
console.log(evens);
_x000D_
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_


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;
}

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;
}

var remove = function(array, value) {
    var index = null;

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

    return array;
};

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]

Simply

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);
}

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]

Another variation:

if (!Array.prototype.removeArr) {
    Array.prototype.removeArr = function(arr) {
        if(!Array.isArray(arr)) arr=[arr];//let's be nice to people who put a non-array value here.. that could be me!
        var that = this;
        if(arr.length){
            var i=0;
            while(i<that.length){
                if(arr.indexOf(that[i])>-1){
                    that.splice(i,1);
                }else i++;
            }
        }
        return that;
    }
}

It's indexOf() inside a loop again, but on the assumption that the array to remove is small relative to the array to be cleaned; every removal shortens the while loop.


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

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

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

console.log(array)
_x000D_
_x000D_
_x000D_


Check out this way:

delete this.arrayName[this.arrayName.indexOf(value)];

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete


You can use without or pull from Lodash:

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

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')
    

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.


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

//This function allows remove even array from array
var removeFromArr = function(arr, elem) { 
    var i, len = arr.length, new_arr = [],
    sort_fn = function (a, b) { return a - b; };
    for (i = 0; i < len; i += 1) {
        if (typeof elem === 'object' && typeof arr[i] === 'object') {
            if (arr[i].toString() === elem.toString()) {
                continue;
            } else {                    
                if (arr[i].sort(sort_fn).toString() === elem.sort(sort_fn).toString()) {
                    continue;
                }
            }
        }
        if (arr[i] !== elem) {
            new_arr.push(arr[i]);
        }
    }
    return new_arr;
}

Example of using

var arr = [1, '2', [1 , 1] , 'abc', 1, '1', 1];
removeFromArr(arr, 1);
//["2", [1, 1], "abc", "1"]

var arr = [[1, 2] , 2, 'a', [2, 1], [1, 1, 2]];
removeFromArr(arr, [1,2]);
//[2, "a", [1, 1, 2]]

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]

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.


ES6 way.

const commentsWithoutDeletedArray = commentsArray.filter(comment => comment.Id !== commentId);

You can use lodash pull function

_x000D_
_x000D_
var ary = ['three', 'seven', 'eleven'];_x000D_
_.pull(ary, 'seven'); // ['three', 'eleven']_x000D_
console.log(ary)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.6.1/lodash.js"></script>
_x000D_
_x000D_
_x000D_


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');

A one-liner will do it,

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

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

// In ECMA6 (arrow function syntax):
var filteredAry = ary.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).


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' ]

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.


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');

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

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