Home How do I remove a particular element from an array in JavaScript?
Reply: 30

How do I remove a particular element from an array in JavaScript?

Walker
1#
Walker Published in 2011-04-23 22:17:18Z

I have an array of integers, and I'm using the .push() method to add elements to it.

Is there a simple way to remove a specific element from an array? The equivalent of something like array.remove(int);.

I have to use core JavaScript - no frameworks are allowed.

Just a student
2#
Just a student Reply to 2017-06-06 13:21:57Z

First, find the index of the element you want to remove:

var array = [2, 5, 9];
var index = array.indexOf(5);

Note: browser support for indexOf is limited; it is not supported in Internet Explorer 7 and 8.

Then remove it with splice:

if (index > -1) {
    array.splice(index, 1);
}

The second parameter of splice is the number of elements to remove. Note that splice modifies the array in place and returns a new array containing the elements that have been removed.


If you need indexOf in an unsupported browser, try the following polyfill. Find more info about this polyfill here.

Array.prototype.indexOf || (Array.prototype.indexOf = function(d, e) {
    var a;
    if (null == this) throw new TypeError('"this" is null or not defined');
    var c = Object(this),
        b = c.length >>> 0;
    if (0 === b) return -1;
    a = +e || 0;
    Infinity === Math.abs(a) && (a = 0);
    if (a >= b) return -1;
    for (a = Math.max(0 <= a ? a : b - Math.abs(a), 0); a < b;) {
        if (a in c && c[a] === d) return a;
        a++
    }
    return -1
});
Antoine
3#
Antoine Reply to 2017-09-25 04:56:18Z
Array.prototype.remByVal = function(val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] === val) {
            this.splice(i, 1);
            i--;
        }
    }
    return this;
}
//Call like
[1, 2, 3, 4].remByVal(3);

Array.prototype.remByVal = function(val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] === val) {
            this.splice(i, 1);
            i--;
        }
    }
    return this;
}

var rooms = ['hello', 'something']

rooms = rooms.remByVal('hello')

console.log(rooms)

Peter Olson
4#
Peter Olson Reply to 2013-05-23 18:10:45Z

I don't know how you are expecting array.remove(int) to behave. There are three possibilities I can think of that you might be wanting.

To remove an element of an array at an index i:

array.splice(i, 1);

If you want to remove every element with value number from the array:

for(var i = array.length - 1; i >= 0; i--) {
    if(array[i] === number) {
       array.splice(i, 1);
    }
}

If you just want to make the element at index i no longer exist, but you don't want the indexes of the other elements to change:

delete array[i];
max taldykin
5#
max taldykin Reply to 2014-07-10 22:43:25Z

Depends on whether you want to keep an empty spot or not.

If you do want an empty slot, delete is fine:

delete array[ index ];

If you don't, you should use the splice method:

array.splice( index, 1 );

And if you need the value of that item, you can just store the returned array's element:

var value = array.splice( index, 1 )[0];

In case you want to do it in some order, you can use array.pop() for the last one or array.shift() for the first one (and both return the value of the item too).

And if you don't know the index of the item, you can use array.indexOf( item ) to get it (in a if() to get one item or in a while() to get all of them). array.indexOf( item ) returns either the index or -1 if not found. 

Loupax
6#
Loupax Reply to 2014-09-05 07:59:57Z

If you want a new array with the deleted positions removed, you can always delete the specific element and filter out the array. It might need an extension of the array object for browsers that don't implement the filter method but in the long term its easier since all you do is this:

var my_array = [1,2,3,4,5,6];
delete my_array[4];
console.log(my_array.filter(function(a){return typeof a !== 'undefined';}));

Should display [1, 2, 3, 4, 6]

Sasa
7#
Sasa Reply to 2017-10-03 12:04:03Z

There are two major approaches:

  1. splice(): anArray.splice(index, 1);

  2. delete: delete anArray[index];

Be careful when you use delete for an array. It is good for deleting attributes of objects but not so good for arrays. It is better to use splice for arrays.

Keep in mind that when you use delete for an array you could get wrong results for anArray.length. In other words, delete would remove the element but wouldn't update the value of length property.

You can also expect to have holes in index numbers after using delete, e.g. you could end up with having indexes 1,3,4,8,9,11 and length as it was before using delete. In that case, all indexed for loops would crash, since indexes are no longer sequential.

If you are forced to use delete for some reason, then you should use for each loops when you need to loop through arrays. As the matter of fact, always avoid using indexed for loops, if possible. That way the code would be more robust and less prone to problems with indexes.

zykadelic
8#
zykadelic Reply to 2017-09-01 22:41:13Z

Update: This method is recommended only if you cannot use ECMAScript 2015 (formerly known as ES6). If you can use it, other answers here provide much neater implementations.


This gist here will solve your problem, and also deletes all occurrences of the argument instead of just 1 (or a specified value).

Array.prototype.destroy = function(obj){
    // Return null if no objects were found and removed
    var destroyed = null;

    for(var i = 0; i < this.length; i++){

        // Use while-loop to find adjacent equal objects
        while(this[i] === obj){

            // Remove this[i] and store it within destroyed
            destroyed = this.splice(i, 1)[0];
        }
    }

    return destroyed;
}

Usage:

var x = [1, 2, 3, 3, true, false, undefined, false];

x.destroy(3);         // => 3
x.destroy(false);     // => false
x;                    // => [1, 2, true, undefined]

x.destroy(true);      // => true
x.destroy(undefined); // => undefined
x;                    // => [1, 2]

x.destroy(3);         // => null
x;                    // => [1, 2]
Ekramul Hoque
9#
Ekramul Hoque Reply to 2014-05-24 07:02:53Z

Check out this code. It works in every major browser.

remove_item = function (arr, value) {
    var b = '';
    for (b in arr) {
        if (arr[b] === value) {
            arr.splice(b, 1);
            break;
        }
    }
    return arr;
}

Call this function

remove_item(array,value);
yckart
10#
yckart Reply to 2013-05-13 12:22:07Z

You can iterate over each array-item and splice it if it exist in your array.

function destroy(arr, val) {
    for (var i = 0; i < arr.length; i++) if (arr[i] === val) arr.splice(i, 1);
    return arr;
}
Enrico
11#
Enrico Reply to 2013-08-07 12:57:55Z

Create new array:

var my_array = new Array();

Add elements to this array:

my_array.push("element1");

The function indexOf (Returns index or -1 when not found) :

var indexOf = function(needle) 
{
    if(typeof Array.prototype.indexOf === 'function') // newer browsers
    {
        indexOf = Array.prototype.indexOf;
    } 
    else // older browsers
    {
        indexOf = function(needle) 
        {
            var index = -1;

            for(var i = 0; i < this.length; i++) 
            {
                if(this[i] === needle) 
                {
                    index = i;
                    break;
                }
            }
            return index;
        };
    }

    return indexOf.call(this, needle);
};

Check index of this element (tested with firefox and IE8+):

var index = indexOf.call(my_array, "element1");

Remove 1 element located at index from the array

my_array.splice(index, 1);
Peter Mortensen
12#
Peter Mortensen Reply to 2015-07-11 09:46:59Z

A friend was having issues in Internet Explorer 8, and showed me what he did. I told him it was wrong, and he told me he got the answer here. The current top answer will not work in all browsers (Internet Explorer 8 for example), and it will only remove the first occurrence of the item.

Remove ALL instances from an array

  function remove(arr, item) {
      for(var i = arr.length; i--;) {
          if(arr[i] === item) {
              arr.splice(i, 1);
          }
      }
  }

It loops through the array backwards (since indices and length will change as items are removed) and removes the item if it's found. It works in all browsers.

Jeff Noel
13#
Jeff Noel Reply to 2013-08-12 17:56:39Z

You can do a backward loop to make sure not to screw up the indexes, if there are multiple instances of the element.

var myElement = "chocolate";
var myArray = ['chocolate', 'poptart', 'poptart', 'poptart', 'chocolate', 'poptart', 'poptart', 'chocolate'];

/* Important code */
for (var i = myArray.length - 1; i >= 0; i--) {
    if (myArray[i] == myElement) myArray.splice(i, 1);
}

Live Demo

magiccrafter
14#
magiccrafter Reply to 2015-02-16 12:51:30Z

John Resig posted a good implementation:

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

If you don’t want to extend a global object, you can do something like the following, instead:

// Array Remove - By John Resig (MIT Licensed)
Array.remove = function(array, from, to) {
    var rest = array.slice((to || from) + 1 || array.length);
    array.length = from < 0 ? array.length + from : from;
    return array.push.apply(array, rest);
};

But the main reason I am posting this is to warn users against the alternative implementation suggested in the comments on that page (Dec 14, 2007):

Array.prototype.remove = function(from, to){
  this.splice(from, (to=[0,from||1,++to-from][arguments.length])<0?this.length+to:to);
  return this.length;
};

It seems to work well at first, but through a painful process I discovered it fails when trying to remove the second to last element in an array. For example, if you have a 10-element array and you try to remove the 9th element with this:

myArray.remove(8);

You end up with an 8-element array. Don't know why but I confirmed John's original implementation doesn't have this problem.

slosd
15#
slosd Reply to 2015-09-11 12:47:59Z

There is no need to use indexOf or splice. However, it performs better if you only want to remove one occurrence of an element.

Find and move (move):

function move(arr, val) {
  var j = 0;
  for (var i = 0, l = arr.length; i < l; i++) {
    if (arr[i] !== val) {
      arr[j++] = arr[i];
    }
  }
  arr.length = j;
}

Use indexOf and splice (indexof):

function indexof(arr, val) {
  var i;
  while ((i = arr.indexOf(val)) != -1) {
    arr.splice(i, 1);
  }
}

Use only splice (splice):

function splice(arr, val) {
  for (var i = arr.length; i--;) {
    if (arr[i] === val) {
      arr.splice(i, 1);
    }
  }
}

Run-times on nodejs for array with 1000 elements (average over 10000 runs):

indexof is approximately 10x slower than move. Even if improved by removing the call to indexOf in splice it performs much worse than move.

Remove all occurrences:
    move 0.0048 ms
    indexof 0.0463 ms
    splice 0.0359 ms

Remove first occurrence:
    move_one 0.0041 ms
    indexof_one 0.0021 ms
Don Vincent Preziosi
16#
Don Vincent Preziosi Reply to 2013-09-26 00:12:44Z
  Array.prototype.removeItem = function(a) {
            for (i = 0; i < this.length; i++) {
                if (this[i] == a) {
                    for (i2 = i; i2 < this.length - 1; i2++) {
                        this[i2] = this[i2 + 1];
                    }
                    this.length = this.length - 1
                    return;
                }
            }
        }

    var recentMovies = ['Iron Man', 'Batman', 'Superman', 'Spiderman'];
    recentMovies.removeItem('Superman');
NullPointer
17#
NullPointer Reply to 2013-10-08 10:09:53Z

I also ran in the situation where I had to remove an element from Array. .indexOf was not working in IE* so sharing my working jQuery.inArray() solution.

var index = jQuery.inArray(val,arr);
if (index > -1) {
    arr.splice(index, 1);
    //console.log(arr);
}
Ujeenator
18#
Ujeenator Reply to 2017-04-14 14:49:05Z

Edited on 2016 october

  • Do it simple, intuitive and explicit (https://en.wikipedia.org/wiki/Occam%27s_razor)
  • Do it immutable (original array stay unchanged)
  • Do it with standard JS functions, if your browser don't support them - use polyfill

In this code example I use "array.filter(...)" function to remove unwanted items from array, this function doesn't change the original array and creates a new one. If your browser don't support this function (e.g. IE before version 9, or Firefox before version 1.5), consider using the filter polyfill from Mozilla.

Removing item (ECMA-262 Edition 5 code aka oldstyle JS)

var value = 3

var arr = [1, 2, 3, 4, 5, 3]

arr = arr.filter(function(item) { 
    return item !== value
})

console.log(arr)
// [ 1, 2, 4, 5 ]

Removing item (ES2015 code)

let value = 3

let arr = [1, 2, 3, 4, 5, 3]

arr = arr.filter(item => item !== value)

console.log(arr)
// [ 1, 2, 4, 5 ]

IMPORTANT ES2015 "() => {}" arrow function syntax is not supported in IE at all, Chrome before 45 version, Firefox before 22 version, Safari before 10 version. To use ES2015 syntax in old browsers you can use BabelJS


Removing multiple items (ES2015 code)

An additional advantage of this method is that you can remove multiple items

let forDeletion = [2, 3, 5]

let arr = [1, 2, 3, 4, 5, 3]

arr = arr.filter(item => !forDeletion.includes(item))
// !!! Read below about array.includes(...) support !!!

console.log(arr)
// [ 1, 4 ]

IMPORTANT "array.includes(...)" function is not supported in IE at all, Chrome before 47 version, Firefox before 43 version, Safari before 9 version and Edge before 14 version so here is polyfill from Mozilla

Removing multiple items (Cutting-edge experimental JavaScript ES2018?)

// array-lib.js

export function remove(...forDeletion) {
    return this.filter(item => !forDeletion.includes(item))
}

// main.js

import { remove } from './array-lib.js'

let arr = [1, 2, 3, 4, 5, 3]

// :: This-Binding Syntax Proposal
// using "remove" function as "virtual method"
// without extending Array.prototype
arr = arr::remove(2, 3, 5)

console.log(arr)
// [ 1, 4 ]

Try it yourself in BabelJS :)

Reference

  • Array.prototype.includes
  • This-Binding Syntax Proposal
  • Functional composition
yckart
19#
yckart Reply to 2014-12-30 16:17:43Z

I'm pretty new to JavaScript and needed this functionality. I merely wrote this:

function removeFromArray(array, item, index) {
  while((index = array.indexOf(item)) > -1) {
    array.splice(index, 1);
  }
}

Then when I want to use it:

//Set-up some dummy data
var dummyObj = {name:"meow"};
var dummyArray = [dummyObj, "item1", "item1", "item2"];

//Remove the dummy data
removeFromArray(dummyArray, dummyObj);
removeFromArray(dummyArray, "item2");

Output - As expected. ["item1", "item1"]

You may have different needs than I, so you can easily modify it to suit them. I hope this helps someone.

Ardi
20#
Ardi Reply to 2017-10-04 16:35:41Z

Based on all the answers which were mainly correct and taking into account the best practices suggested (especially not using Array.prototype directly), I came up with the below code:

function arrayWithout(arr, values) {
  var isArray = function(canBeArray) {
    if (Array.isArray) {
      return Array.isArray(canBeArray);
    }
    return Object.prototype.toString.call(canBeArray) === '[object Array]';
  };

  var excludedValues = (isArray(values)) ? values : [].slice.call(arguments, 1);
  var arrCopy = arr.slice(0);

  for (var i = arrCopy.length - 1; i >= 0; i--) {
    if (excludedValues.indexOf(arrCopy[i]) > -1) {
      arrCopy.splice(i, 1);
    }
  }

  return arrCopy;
}

Reviewing the above function, despite the fact that it works fine, I realised there could be some performance improvement. Also using ES6 instead of ES5 is a much better approach. To that end, this is the improved code:

const arrayWithoutFastest = (() => {
  const isArray = canBeArray => ('isArray' in Array) 
    ? Array.isArray(canBeArray) 
    : Object.prototype.toString.call(canBeArray) === '[object Array]';

  let mapIncludes = (map, key) => map.has(key);
  let objectIncludes = (obj, key) => key in obj;
  let includes;

  function arrayWithoutFastest(arr, ...thisArgs) {
    let withoutValues = isArray(thisArgs[0]) ? thisArgs[0] : thisArgs;

    if (typeof Map !== 'undefined') {
      withoutValues = withoutValues.reduce((map, value) => map.set(value, value), new Map());
      includes = mapIncludes;
    } else {
      withoutValues = withoutValues.reduce((map, value) => { map[value] = value; return map; } , {}); 
      includes = objectIncludes;
    }

    const arrCopy = [];
    const length = arr.length;

    for (let i = 0; i < length; i++) {
      // If value is not in exclude list
      if (!includes(withoutValues, arr[i])) {
        arrCopy.push(arr[i]);
      }
    }

    return arrCopy;
  }

  return arrayWithoutFastest;  
})();

How to use:

const arr = [1,2,3,4,5,"name", false];

arrayWithoutFastest(arr, 1); // will return array [2,3,4,5,"name", false]
arrayWithoutFastest(arr, 'name'); // will return [2,3,4,5, false]
arrayWithoutFastest(arr, false); // will return [2,3,4,5]
arrayWithoutFastest(arr,[1,2]); // will return [3,4,5,"name", false];
arrayWithoutFastest(arr, {bar: "foo"}); // will return the same array (new copy)

I am currently writing a blog post in which I have benchmarked several solutions for Array without problem and compared the time it takes to run. I will update this answer with the link once I finish that post. Just to let you know, I have compared the above against lodash's without and in case the browser supports Map, it beats lodash! Notice that I am not using Array.prototype.indexOf or Array.prototype.includes as wrapping the exlcudeValues in a Map or Object makes querying faster! (https://jsperf.com/array-without-benchmark-against-lodash)

Nigel Sheridan-Smith
21#
Nigel Sheridan-Smith Reply to 2014-09-05 07:21:44Z

In CoffeeScript:

my_array.splice(idx, 1) for ele, idx in my_array when ele is this_value
wharding28
22#
wharding28 Reply to 2014-02-19 22:20:53Z

I know there are a lot of answers already, but many of them seem to over complicate the problem. Here is a simple, recursive way of removing all instances of a key - calls self until index isn't found. Yes, it only works in browsers with indexOf, but it's simple and can be easily polyfilled.

Stand-alone function

function removeAll(array, key){
    var index = array.indexOf(key);

    if(index === -1) return;

    array.splice(index, 1);
    removeAll(array,key);
}

Prototype method

Array.prototype.removeAll = function(key){
    var index = this.indexOf(key);

    if(index === -1) return;

    this.splice(index, 1);
    this.removeAll(key);
}
Salvador Dali
23#
Salvador Dali Reply to 2014-02-10 22:06:01Z

You can do it easily with filter method:

function remove(arrOriginal, elementToRemove){
    return arrOriginal.filter(function(el){return el !== elementToRemove});
}
console.log( remove([1, 2, 1, 0, 3, 1, 4], 1) );

This removes all elements from the array and also works faster then combination of slice and indexOf

Peter Mortensen
24#
Peter Mortensen Reply to 2014-06-22 22:03:43Z

I like this version of splice, removing an element by its value using $.inArray:

$(document).ready(function(){
    var arr = ["C#","Ruby","PHP","C","C++"];
    var itemtoRemove = "PHP";
    arr.splice($.inArray(itemtoRemove, arr),1);
});
amd
25#
amd Reply to 2016-12-26 10:57:02Z

Too old to reply, but may it help someone, by providing a predicate instead of a value.

NOTE: it will update the given array, and return affected rows

Usage

var removed = helper.removeOne(arr, row => row.id === 5 );

var removed = helper.remove(arr, row => row.name.startsWith('BMW'));

Definition

var helper = {

    // Remove and return the first occurrence     

    removeOne: function(array, predicate) {
        for (var i = 0; i < array.length; i++) {
            if (predicate(array[i])) {
                return array.splice(i, 1);
            }
        }
    },

    // Remove and return all occurrences  

    remove: function(array, predicate) {
        var removed = [];

        for (var i = 0; i < array.length;) {

            if (predicate(array[i])) {
                removed.push(array.splice(i, 1));
                continue;
            }

            i++;                
        }

        return removed;
    }
};
Peter Mortensen
26#
Peter Mortensen Reply to 2017-05-21 11:29:54Z

Underscore.js can be used to solve issues with multiple browsers. It uses in-build browser methods if present. If they are absent like in the case of older Internet Explorer versions it uses its own custom methods.

A simple example to remove elements from array (from the website):

_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); // => [2, 3, 4]
penguin
27#
penguin Reply to 2014-06-25 23:57:30Z
var index,
    input = [1,2,3],
    indexToRemove = 1;
    integers = [];

for (index in input) {
    if (input.hasOwnProperty(index)) {
        if (index !== indexToRemove) {
            integers.push(result); 
        }
    }
}
input = integers;

This solution will take an array of input and will search through the input for the value to remove. This will loop through the entire input array and the result will be a second array integers that has had the specific index removed. The integers array is then copied back into the input array.

Peter Mortensen
28#
Peter Mortensen Reply to 2015-07-11 09:48:58Z

Use jQuery's InArray:

A = [1, 2, 3, 4, 5, 6];
A.splice($.inArray(3, A), 1);
//It will return A=[1, 2, 4, 5, 6]`   

Note: inArray will return -1, if the element was not found.

Peter Mortensen
29#
Peter Mortensen Reply to 2015-07-11 09:49:40Z

Removing the value with index and splice!

function removeArrValue(arr,value) {
    var index = arr.indexOf(value);
    if (index > -1) {
        arr.splice(index, 1);
    }
    return arr;
}
Peter Mortensen
30#
Peter Mortensen Reply to 2015-07-11 09:50:20Z

If you must support older versions of Internet Explorer, I recommend using the following polyfill (note: this is not a framework). It's a 100% backwards-compatible replacement of all modern array methods (JavaScript 1.8.5 / ECMAScript 5 Array Extras) that works for Internet Explorer 6+, Firefox 1.5+, Chrome, Safari, & Opera.

https://github.com/plusdude/array-generics

rncrtr
31#
rncrtr Reply to 2015-01-07 19:53:17Z

There are many fantastic answers here, but for me, what worked most simply wasn't removing my element from the array completely but simply setting the value of it to null. This works for most cases I have, and is a good solution since I will be using the variable later and don't want it gone, just empty for now. Also, this approach is completely cross-browser compatible.

array.key = null;
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.417782 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO