By Walker


2011-04-23 22:17:18 8 Comments

I have an array of Numbers, 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(number);.

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

30 comments

@codepleb 2019-04-13 08:51:30

Oftentimes it's better to just create a new array with the filter function.

let array = [1,2,3,4];
array = array.filter(i => i !== 4); // [1,2,3]

This also improves readability imho. I'm not a fan of slice, although it know sometimes you should go for it.

@Yanis-git 2019-06-09 14:20:45

hello, because you use const keyword you can't override original array. You may switch to let

@codepleb 2019-06-11 05:26:42

@Yanis-git My bad, thx.

@Atchutha rama reddy Karri 2019-04-24 04:32:50

[2,3,5].filter(i => ![5].includes(i))

@Siddhartha 2019-04-17 18:18:26

var array = [1,2,3];
console.log('Array-First',array); // Array-First 1,2,3
array.splice(1,1);
console.log('Array-Second',array); // Array-Second 1,3

@Flavio Copes 2018-05-04 05:17:29

Here are a few ways to remove an item from an array using JavaScript.

All the method described do not mutate the original array, and instead create a new one.

If you know the index of an item

Suppose you have an array, and you want to remove an item in position i.

One method is to use slice():

const items = ['a', 'b', 'c', 'd', 'e', 'f']
const i = 3
const filteredItems = items.slice(0, i).concat(items.slice(i+1, items.length))

console.log(filteredItems)

slice() creates a new array with the indexes it receives. We simply create a new array, from start to the index we want to remove, and concatenate another array from the first position following the one we removed to the end of the array.

If you know the value

In this case, one good option is to use filter(), which offers a more declarative approach:

const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valueToRemove = 'c'
const filteredItems = items.filter(item => item !== valueToRemove)

console.log(filteredItems)

This uses the ES6 arrow functions. You can use the traditional functions to support older browsers:

const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valueToRemove = 'c'
const filteredItems = items.filter(function(item) {
  return item !== valueToRemove
})

console.log(filteredItems)

or you can use Babel and transpile the ES6 code back to ES5 to make it more digestible to old browsers, yet write modern JavaScript in your code.

Removing multiple items

What if instead of a single item, you want to remove many items?

Let's find the simplest solution.

By index

You can just create a function and remove items in series:

const items = ['a', 'b', 'c', 'd', 'e', 'f']

const removeItem = (items, i) =>
  items.slice(0, i-1).concat(items.slice(i, items.length))

let filteredItems = removeItem(items, 3)
filteredItems = removeItem(filteredItems, 5)
//["a", "b", "c", "d"]

console.log(filteredItems)

By value

You can search for inclusion inside the callback function:

const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valuesToRemove = ['c', 'd']
const filteredItems = items.filter(item => !valuesToRemove.includes(item))
// ["a", "b", "e", "f"]

console.log(filteredItems)

Avoid mutating the original array

splice() (not to be confused with slice()) mutates the original array, and should be avoided.

(originally posted at https://flaviocopes.com/how-to-remove-item-from-array/)

@Salomao Rodrigues 2019-03-17 17:02:30

I think that in your example you want items.slice(0, i).concat(items.slice(i+1, items.length)), (0,i) instead of (0, i-1) because the array 'end' element is not included in the result. Also, i+1 is ok for the second part as it returns an empty array if it goes out of bounds.

@Flavio Copes 2019-04-14 16:40:33

You are right. I fixed that on my blog some time ago, but never changed it in the answer! Thank you for telling me

@Max Alexander Hanna 2019-01-08 14:34:36

Removing a particular element/string from an array can be done in a one liner: I still think this is the most elegant one liner you can get for this type of problem :

theArray.splice(theArray.indexOf("stringToRemoveFromArray"), 1);

where 'theArray' is the array you want to remove something particular from, and 1 is the amount of elements you want to remove.

@jdavid05 2019-04-03 11:52:46

This is the answer that worked for me when trying to update an array based on radio button toggling.

@Fusion 2019-04-06 23:35:39

Beware, if "stringToRemoveFromArray" is not located your in array, this will remove last element of array.

@AmerllicA 2018-10-30 17:37:42

I wanna answer based on ES6. Assume, you have an array like below:

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

If you wanna delete special index like 2, write below code:

arr.splice(2, 1); //=> arr became [1,2,4]

But if you wanna delete a special item like 3 and you don't know its index do like below:

arr = arr.filter(e => e !== 3); //=> arr became [1,2,4]

Hint: please use an arrow function for filter callback unless you will get an empty array.

@Dejan.S 2018-12-18 09:24:36

the last option will return a empty array

@AmerllicA 2018-12-18 09:35:11

@Dejan.S, I surprised, what's your array, and what you want to omit from your array?

@Dejan.S 2018-12-18 09:39:43

It was my bad, I used regular function and had to explicitly do a return statement. Sorry about that :)

@AmerllicA 2018-12-18 11:50:51

@Dejan.S, I edited the answer for some mistakes like your mistake and add a hint, if you downvote me, you can upvote now.

@Tom Wadley 2011-04-23 22:23:50

Find the index of the array element you want to remove, then remove that index with splice.

The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

var array = [2, 5, 9];
console.log(array)
var index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1);
}
// array = [2, 9]
console.log(array);

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.

@Tom Wadley 2011-04-23 22:28:10

@Peter, yes you might be right. This article explains more and has a workaround for incompatible browsers: developer.mozilla.org/en/JavaScript/Reference/Global_Objects‌​/…

@zykadelic 2013-03-02 02:33:52

You can ease up usage of this by adding a delete function on the array prototype. I’ve taken use of your example in a gist that deletes all targeted elements in the array instead of just 1.

@zykadelic 2013-03-07 21:50:54

It’s too late to edit my last comment but I just want to correct myself. Calling delete on an array is no go in IE 8. I’ve updated the gist to use destroy instead.

@Adrian P. 2013-09-06 16:44:17

Dangerous! If you are working with dynamic values (add and remove dynamic values from array) and value is not exist in array (the index become -1) the code above will remove the last element of the array.

@Alexandre Wiechers Vaz 2013-09-26 18:18:20

Does splice preserve the array order??

@TheZ 2013-12-11 19:18:02

@AlexandreWiechersVaz Of course it preserves order, if it didn't then it would be absolutely worthless

@user2443147 2014-06-08 10:42:27

You can overcome the IE browser support problem by including the code given here

@Chris 2014-07-07 14:00:23

indexOf kept returning -1 in my version of Firefox (30.0). I ended up just writing a simple for loop to find the index and it works fine...

@Curtis Yallop 2014-07-31 23:20:49

Related question: How to do it with jQuery (jQuery.grep). stackoverflow.com/questions/3596089/…

@Adrian P. 2015-01-19 13:51:48

@UpTheCreek I thought it is clear: having an array filled dynamically means sometimes you have an empty array. By using this solution you can try to remove the last element which not exist. The result is a JS error. If you have the same number of elements in this array then all is good. You can use it.

@UpTheCreek 2015-01-19 15:47:21

@AdrianP. array.indexOf(testValue) on empty array will be -1, and if you're testing for that then no splice. Maybe the answer has changed since.

@CodyBugstein 2015-01-29 12:52:13

It doesn't work. See my JSFiddle jsfiddle.net/bB7Ey/28

@aroth 2015-02-06 01:53:13

And note that if you're working with non-primitive types, Array.indexOf() does not test for object equality. It only works if you pass the exact same object reference. See: jsfiddle.net/b0e7zsm3

@klenium 2015-08-25 19:52:56

@Imray .splice returns the removed element, not the new array. jsfiddle.net/bB7Ey/85

@Thaenor 2015-10-18 15:20:04

This isn't a good method to use when iterating arrays. What happens in my case is that it's not the element in question that gets removed but the one after it. Also, I've used this with jQuery's .each function and it causes issues as the array becomes smaller but it's lenght is still iterated (meaning it will try access empty values in the end). I couldn't reproduce the last error but the first I can show it in this JSBin (jsbin.com/xufovopoji/edit?html,js,output)

@Justin 2015-12-14 20:02:28

Don't use this method with a for loop, instead use while(myarry.lenth--). The reason is "the array is being re-indexed when you do a .splice(), which means you'll skip over an index when one is removed, and your cached .length is obsolete." stackoverflow.com/a/9882349/922522

@Lukas 2016-01-13 08:08:26

IE 7, IE8, IE9, IE10 ar unsupported by Microsoft itself, why should web developers support those old browsers? Just show notification about upgrading the browser! support.microsoft.com/en-us/lifecycle/…

@Chinmaya B 2016-02-14 15:38:48

Why not use delete method directly like delete arname [index]; ?

@Tommy Steimel 2016-04-11 18:27:15

@Creator that leaves an undefined in the array. jsfiddle.net/dsup87xL

@vard 2016-04-26 14:30:27

@LukasLiesis This is never and has never been a developer choice. When you are addressing a specific audience like public organisations that can't upgrade for internal reasons or non US/EU countries (which still have a lot of users on WinXP), you'll have to provide support for IE8 for those users. It just depend of for whom your website is for, you can't have a generic approach on this matter.

@Alexander Craggs 2016-06-10 22:43:54

Can anyone explain how the polyfill actually works? Code looks very interesting. You're comparing infinity (observing variable type) to Math.abs(a) && (a = 0) and doing some incredible other stuff involving >>>?

@John Christian De Chavez 2016-07-12 03:42:06

array.splice() function doesnt work if my index is token with a length of 16 and delete arname [index]; is working for me

@John Christian De Chavez 2016-07-12 04:03:18

Update: i found this post stackoverflow.com/questions/8173210/…. and now i know the difference of splice and delete.

@Константин Ван 2016-09-04 14:04:59

To get the index of an object in an Array by its property, you can use TheArray.map(function(e) {return e.property;}).indexOf(PROPERTY_VALUE_TO_SEARCH)(IE 9+), or TheArray.map(e => e.property).indexOf(PROPERTY_VALUE_TO_SEARCH) if your browser supports Arrow Functons.

@Aykut Yaman 2017-01-11 15:22:15

As @klenium said, the splice() method changes the content of an array, it does not return a new array.

@Sarath S Nair 2017-01-30 04:26:31

arr = [1,2,3,4,5] var filtered = arr.filter(function(ele){ return ele != 3; }); //filtered = [1,2,4,5];

@Greg 2017-03-06 16:27:17

OPs provided spec does not specify an array of unique integers. indexOf will only return the position of the first found match (from optional "fromIndex").

@heringer 2017-05-04 12:30:57

Not sure if it is worth a note, but be aware for the behavior in case of duplicated items. Only the first one is removed in this approach.

@iulial 2017-06-28 13:53:26

In the era of immutability, better use Array.filter() or Array.slice() example here

@Megh 2017-09-26 18:31:05

Wont it shift array Index to lower level and subsequent element wont be available in list if we are looping through an array.

@Marcelo Rafael 2017-10-14 04:28:57

Splice is the best, with delete my JSON.stringify has a null on place that deleted

@HamidReza Heydari 2017-12-16 08:59:01

use array.filter() is the best way

@MrClan 2018-01-08 09:40:13

@TomWadley why the first if condition is (index > -1) instead of (index != -1) ?

@Tom Wadley 2018-01-11 16:48:28

@MrClan from the docs, it looks like indexOf() will never return a negative number other than -1 so != -1 or !== -1 would be perfectly fine. No particular reason for using > -1.

@Chang 2019-01-27 18:14:59

Splice can be best used when you know the index and all the desired values to be delete, are in a sequence. If you don't know the index, here are some good alternates using splice, filter, shift, pop- stackoverflow.com/a/54390552/8958729

@Jonny 2019-01-28 15:42:46

On a small array, why not just use a simple for loop?

@Chang 2019-01-27 16:55:52

To remove particular element or subsequent elements, Array.splice() method works well. The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements and it returns the removed item(s).

Syntax: array.splice(index, deleteCount, item1, ....., itemX)

Here index is mandatory and rest arguments are optional.

For example:

let arr = [1, 2, 3, 4, 5, 6];
arr.splice(2,1);
console.log(arr);
// [1, 2, 4, 5, 6]

Note: Array.splice() method can be used if you know the index of the element which you want to delete. But we may have a few more cases as mentioned below-

  1. In case you want to delete just last element, you can use Array.pop()

  2. In case you want to delete just first element, you can use Array.shift()

  3. If you know the element alone but not the position(or index) of the element, and want to delete all matching elements using Array.filter() method:

    let arr = [1, 2, 1, 3, 4, 1, 5, 1];
    
    let newArr = arr.filter(function(val){
        return val !== 1;
     });
     //newArr => [2, 3, 4, 5]
    

OR by using splice() method as-

let arr = [1, 11, 2, 11, 3, 4, 5, 11, 6, 11];
    for( let i = 0; i < arr.length-1; i++){
       if ( arr[i] === 11) {
         arr.splice(i, 1); 
       }
    }
    console.log(arr);
    // [1, 2, 3, 4, 5, 6]

OR suppose we want to delete del from the Array arr:

let arr = [1, 2, 3, 4, 5, 6];
let del = 4;
if(arr.indexOf(4) >= 0) {
arr.splice(arr.indexOf(4), 1)
}

OR

let del = 4;
for(var i = arr.length - 1; i >= 0; i--) {
    if(arr[i] === del) {
       arr.splice(i, 1);
    }
}
  1. If you know the element alone but not the position(or index) of the element, and want to delete just very first matching element using splice() method:

    let arr = [1, 11, 2, 11, 3, 4, 5, 11, 6, 11];
    
    for( let i = 0; i < arr.length-1; i++){
      if ( arr[i] === 11) {
        arr.splice(i, 1);
        break;
      }
    }
    console.log(arr);
    // [1, 11, 2, 11, 3, 4, 5, 11, 6, 11]
    

@Chang 2019-01-27 19:46:27

Note: Array.prototype.filter is ECMAScript 5.1 (No IE8)

@Little Brain 2019-05-30 14:31:47

For option 4, should the loop be 'i < arr.length' not 'i < arr.length-1'?

@Ashish 2019-02-05 05:34:45

Splice, filter and delete to remove element from array

Every array have their index and it helps to delete particular element with their index.

The splice() method

array.splice(index, 1); 1st parameter is index and second is the number of element you

want to delete from that index.

So for single element we use 1.

The delete method

delete array[index]

The filter() method

If you want to delete element which is repeated in array then filter the array.

removeAll =array.filter( e=> e != elem );

where elem is the element you want to remove from array and array is your array name

@alejoko 2019-02-02 14:41:59

Taking profit of reduce method as following:

case a) if u need to remove element by index:

function remove(arr, index) {
  return arr.reduce((prev, x, i) => prev.concat(i !== index ? [x] : []), []);
}

case b) if u need to remove element by the value of the element (int):

function remove(arr, value) {
  return arr.reduce((prev, x, i) => prev.concat(x !== value ? [x] : []), []);
}

So at this way we can return a new array (will be a cool functional way - more much better than use push or splice) with the element removed.

@Ashish 2019-01-28 10:47:18

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements.

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

start

Index at which to start changing the array (with origin 0). If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end of the array (with origin -1) and will be set to 0 if absolute value is greater than the length of the array.

deleteCount Optional

An integer indicating the number of old array elements to remove. If deleteCount is omitted, or if its value is larger than array.length - start (that is, if it is greater than the number of elements left in the array, starting at start), then all of the elements from start through the end of the array will be deleted. If deleteCount is 0 or negative, no elements are removed. In this case, you should specify at least one new element (see below).

item1, item2, ... Optional

The elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array.

For more referene kindly go through :

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

@Shahriar Ahmad 2018-12-31 23:33:27

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

arr.splice(0,1)

console.log(arr)

Output [2, 3, 4, 5];

@Sebastien H. 2018-12-21 15:10:47

Yet another answer, to me the simpler is the better, and as we are in 2018 (near 2019) i give you this (near) one liner to answer the original question :

Array.prototype.remove = function (value) { 
    return this.filter(f => f != value) 
}

The useful thing is that you can use it in a curry expression such as :

[1,2,3].remove(2).sort()

@Peter Olson 2011-04-23 22:20:56

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

@Felix Kling 2013-01-27 15:30:48

delete is not the correct way to remove an element from an array!

@Peter Olson 2013-01-27 15:36:52

@FelixKling It depends, it works if you want to make it so that array.hasOwnProperty(i) returns false and have the element at that position return undefined. But I'll admit that that's not a very common thing to want to do.

@diosney 2013-02-17 03:44:59

delete will not update the length of the array neither really erases the element, only replaces it with the special value undefined.

@Peter Olson 2013-04-15 19:13:42

@diosney I don't know what you mean when you say it doesn't really erase the element. Further, it does more than simply replacing the value at that index with undefined: it removes both the index and the value from the array, i.e. after delete array[0], "0" in array will return false.

@Bambax 2013-05-23 18:04:43

for(var i=array.length; i>=0; i--) should be for(var i=array.length-1; i>=0; i--) because indexing starts at 0 (there is no element at array[array.length])

@Pingwin Tux 2014-03-13 09:17:27

Splice is operation on range. Remember that operations on ranges can be expensive (uses more CPU). In this example it is two for loops in fact. We should choose more cheap functions if it is possible.

@Jefferey Cave 2014-10-21 23:00:59

delete is a good mechanism if you are dealing with named properties var array=[];array['red']=1;array['green']=2;array['blue']=3;del‌​ete array['green'];

@Eric Elliott 2014-11-20 00:35:22

@Kavius Don't be too embarrassed. I once read a published book on JS that described "associative arrays" in JavaScript exactly like your comment described them. It's an easy mistake to make if you're approaching JavaScript from another language.

@BenG 2015-08-17 15:20:35

in modern js engines, using: array[i] = null is favored instead of delete array[i]

@Paul 2015-08-19 12:03:07

@BenG, can you provide a reference or two for that statement, or at least explain why it's favored?

@Peter Olson 2015-08-19 23:09:51

@BenG That doesn't make sense: they do different things, how can one be favored?

@BenG 2015-08-21 14:50:27

@Paul it's referenced many places(e.g. smashingmagazine.com/2012/11/…). But the basics of it are that the the underlying JS engine will be faster at garbage collection than if you try to manually, and your code will be easier to comprehend if you explicitly set the value. It can be an easy mistake for someone else reading your code if they see delete array[i] to assume the indices of the remaining elements have been updated

@Sandy Gifford 2018-01-26 20:15:17

@BenG your link doesn't address arrays at all (I think? It's a massive page, I just looked at the section you linked) it only talks about nulling references to namespaces. Nulling elements in an array will still keep the reference alive (garbage collection had better never come for my empty array values)...

@Sasa 2018-05-15 09:13:39

Indexed for loop wouldn't work for all arrays. If you previously used delete on the array, then for loop will crash.

@Grant Gryczan 2018-06-09 05:28:16

Downvoted, because some people will skim over the answer, see the delete operation, and just blindly copy it into their code because it looks about right to them. That's not good! Downvoted.

@Peter Olson 2018-06-11 18:15:01

@GrantGryczan That part of the answer is at the very bottom. It's not my fault if people skip to the bottom and ignore the description describing what it does.

@Grant Gryczan 2018-06-12 00:51:37

You don't give a warning either (let alone in bold), that that isn't how you remove things from arrays. The existence of that line of code in this answer is not useful. Here, let me make an edit. I would just recommend completely removing it though. It doesn't add anything of practicality.

@Peter Olson 2018-06-12 02:27:51

@GrantGryczan Sorry, I disagree. I don't see the need for this to be removed. The text above clearly explains what it does, and it helps people who don't know what delete does to understand why it doesn't work as they expect.

@Sebastien H. 2019-01-04 09:25:04

there are far better ways of doing this, delete is a bad practice on an array

@Ardi 2014-01-28 14:44:55

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!

@Phil 2018-09-12 09:16:36

I had this problem myself (in a situation where replacing the array was acceptable) and solved it with a simple:

var filteredItems = this.items.filter(function (i) {
    return i !== item;
});

To give the above snippet a bit of context:

self.thingWithItems = {
        items: [],
        removeItem: function (item) {
            var filteredItems = this.items.filter(function (i) {
                return i !== item;
            });

            this.items = filteredItems;
        }
    };

This solution should work with both reference and value items. It all depends whether you need to maintain a reference to the original array as to whether this solution is applicable.

@Thilina Sampath 2018-08-07 09:37:25

You have 1 to 9 array and you want remove 5 use below code.

var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];

var newNumberArray = numberArray.filter(m => {
  return m !== 5;
});

console.log("new Array, 5 removed", newNumberArray);


If you want to multiple value ex :- 1,7,8

var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];

var newNumberArray = numberArray.filter(m => {
  return (m !== 1) && (m !== 7) && (m !== 8);
});

console.log("new Array, 5 removed", newNumberArray);


If you want to remove array value in array ex :- [3,4,5]

var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var removebleArray = [3,4,5];

var newNumberArray = numberArray.filter(m => {
    return !removebleArray.includes(m);
});

console.log("new Array, [3,4,5] removed", newNumberArray);

includes supported browser is link

@Zibri 2018-07-22 04:42:19

    Array.prototype.remove = function(start, end) {
        var n = this.slice((end || start) + 1 || this.length);
        return this.length = start < 0 ? this.length + start : start,
        this.push.apply(this, n)
    }

start and end can be negative, in that case they count from the end of the array.
if only start is specified, only one element is removed.
the function returns the new array length.

z=[0,1,2,3,4,5,6,7,8,9];

newlength=z.remove(2,6);

(8) [0, 1, 7, 8, 9]

z=[0,1,2,3,4,5,6,7,8,9];

newlength=z.remove(-4,-2);

(7) [0, 1, 2, 3, 4, 5, 9]

z=[0,1,2,3,4,5,6,7,8,9];

newlength=z.remove(3,-2);

(4) [0, 1, 2, 9]

@Srikrushna Pal 2018-06-28 17:48:41

delete element from last

arrName.pop();

delete element from first

arrName.shift();

delete from middle

arrName.splice(starting index,number of element you wnt to delete);

Ex: arrName.splice(1,1);

delete one element from last

arrName.splice(-1);

Delete by using array index number

 delete arrName[1];

@Ben Lesh 2013-08-10 19:21:23

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.

@gabeno 2014-01-29 20:06:34

@sroes it should not be because the loop starts at i = arr.length -1 or i-- making it same as the max index. arr.length is just an initial value for i. i-- will always be truthy (and reducing by 1 at each loop op) until it equals 0 (a falsy value) and the loop will then stop.

@ujeenator 2015-02-25 13:32:12

Second function is rather inefficient. On every iteration "indexOf" will start search from beginning of array.

@Ben Lesh 2015-03-03 03:12:31

@AmberdeBlack, you're exactly right. Surprised I didn't catch that when I answered: jsperf.com/remove-all-from-array

@Eugene Kuzmenko 2015-03-29 18:01:15

@AmberdeBlack, you were worried about calling indexOf repeatedly, which is actually not even close to being as bad as calling splice on each iteration.

@Eugene Kuzmenko 2015-03-30 09:37:04

@AmberdeBlack, on a collection with more than 1 occurrence of item, it's much better to call the filter method instead arr.filter(function (el) { return el !== item }), avoiding the need to mutate the array multiple times. This consumes slightly more memory, but operates much more efficiently, since there's less work that needs to be done.

@ujeenator 2015-03-30 16:23:56

@AlJey, it's available only from IE9+. There is still a chance that it wouldn't work.

@Eugene Kuzmenko 2015-03-30 18:05:20

@AmberdeBlack, that's not a valid argument at all these days, just do what the filter function does or, better yet, simply include es5-shim.js in your app.

@mintedsky 2015-07-14 23:39:58

This answer worked for me because I needed several items removed but not in any particular order. The backwards progression of the for loop here handles removing items from the array perfectly.

@Athinodoros Sgouromallis 2019-06-17 10:59:19

arr.filter will remove all instances with the undesired attribute or value

@Aram Grigoryan 2018-06-05 14:47:00

I have another good solution for removing from an array:

var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

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

@Sanya Kravchuk 2018-04-13 11:31:04

let array = [5,5,4,4,2,3,4]    
let newArray = array.join(',').replace('5','').split(',')

This example works if you want to remove one current item.

@hygull 2018-05-13 07:41:00

Define a method named remove() on array objects using prototying feature of JavaScript.

Use splice() method to fulfill your requirement.

Please have a look at the below code.

Array.prototype.remove = function(item) {
    // index will have -1 if item does not exist
    // else it will have the index of 1st item found in array
    var index = this.indexOf(item); 

    if (index > -1) {
        // splice() method is used to add/remove items(s) in array
        this.splice(index, 1); 
    }

    return index;
}


var arr = [ 11, 22, 67, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4];

// Printing array
// [ 11, 22, 67, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4];
console.log(arr)

// Removing 67 (getting its index i.e. 2)
console.log("Removing 67")
var index = arr.remove(67)

if (index > 0){
    console.log("Item 67 found at ", index)
} else {
    console.log("Item 67 does not exist in array")
}

// Printing updated array
// [ 11, 22, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4];
console.log(arr)

// ............... Output ................................
// [ 11, 22, 67, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4 ]
// Removing 67
// Item 67 found at  2
// [ 11, 22, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4 ]

Note: Below is the full example code executed on Node.js REPL which describes the use of push(), pop(), shift(), unshift() and splice() methods.

> // Defining an array
undefined
> var arr = [12, 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34];
undefined
> // Getting length of array
undefined
> arr.length;
16
> // Adding 1 more item at the end i.e. pushing an item
undefined
> arr.push(55);
17
> arr
[ 12, 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34, 55 ]
> // Popping item from array (i.e. from end)
undefined
> arr.pop()
55
> arr
[ 12, 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
> // Remove item from beginning
undefined
> arr.shift()
12
> arr
[ 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
> // Add item(s) at beginning
undefined
> arr.unshift(67); // Add 67 at begining of the array and return number of items in updated/new array
16
> arr
[ 67, 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
> arr.unshift(11, 22); // Adding 2 more items at the beginning of array
18
> arr
[ 11, 22, 67, 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
>
> // Define a method on array (temorarily) to remove an item and return the index of removed item; if it is found else return -1
undefined
> Array.prototype.remove = function(item) {
... var index = this.indexOf(item);
... if (index > -1) {
..... this.splice(index, 1); // splice() method is used to add/remove items in array
..... }
... return index;
... }
[Function]
>
> arr
[ 11, 22, 67, 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
>
> arr.remove(45);   // Remove 45 (You will get the index of removed item)
3
> arr
[ 11, 22, 67, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
>
> arr.remove(22)    // Remove 22
1
> arr
[ 11, 67, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
> arr.remove(67)    // Remove 67
1
> arr
[ 11, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
>
> arr.remove(89)    // Remove 89
2
> arr
[ 11, 67, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
>
> arr.remove(100);  // 100 doesn't exist, remove() will return -1
-1
>

Thanks.

@Steven Spungin 2018-04-27 00:07:48

Your question did not indicate if order or distinct values are a requirement.

If you don't care about order, and will not have the same value in the container more than once, use a Set. It will be way faster, and more succinct.

var aSet = new Set();

aSet.add(1);
aSet.add(2);
aSet.add(3);

aSet.delete(2);

@ujeenator 2013-12-19 19:54:26

Edited on 2016 october

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 (ES2016 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

@Ravinder Payal 2017-02-08 14:06:04

but, sometimes we want to remove element from original array(non immutable), for example array used in Angular 2 *ngFor directive

@Greg 2017-03-06 16:46:21

Better than the accepted solution because it does not assume only one occurrence of a match and immutability is preferable

@Nathan 2017-07-17 01:02:59

filter must be much slower for a big array though?

@mench 2017-08-19 11:36:51

What's the point of immutability mentioned if you used assignment of the same variable in your examples? :)

@ujeenator 2017-08-19 12:10:30

@mench because it would be too complex example if I use both reference immutability and data immutability. I would then need to use some kind of state container. Also data immutability is enough to avoid most of side effect errors.

@Soldeplata Saketos 2017-08-28 07:31:58

This is not a good answer, because it creates a new array, thus creates a new reference. It doesn't remove its elements. It creates a new Array and assigns it. So, for instance, having let arr = arr2 = [1,3,2]; and doing that filter arr = arr.filter(el => el !==3) will result on no modification on arr2, while doing the splice, both arrays will be modified.

@highmaintenance 2017-12-12 13:05:30

Super slow method.

@ujeenator 2017-12-12 15:00:41

@Andy in comparison to what method and what scenario?

@ujeenator 2017-12-12 15:01:54

@Nathan in comparison to what method and what scenario? By slower you mean execution time?

@highmaintenance 2017-12-12 16:42:01

@Ujeenator filter is super slow if you need to remove a single element from an array

@tomaytotomato 2018-03-26 20:23:48

This doesn't work if you only want to remove one occurrence of a value from an array. e.g. [1,2,3,3,4,5].filter(num => num == 3) it will remove both values of 3

@Greg 2018-04-05 20:32:10

There is a small mistake in here. As per Array.prototype.includes(), includes is ECMAScript 2016 Spec

@Stephen 2018-05-28 17:23:38

I love the reasoning behind this answer. Remove items by filtering out the ones you don't want. Brilliant!

@Matthew 2018-08-15 12:50:44

This is a great answer. Splice is a specialized function for mutating not filtering. filter may have slower performance but it is safer and better code. Also, you can filter by index by specifying a second argument in the lambda: arr.filter((x,i)=>i!==2)

@Jeffrey Goines 2019-03-10 04:01:18

Be cautious using filter and assignment when the array is referenced by many.

@Alireza 2017-05-10 09:39:00

OK, for example you are having the array below:

var num = [1, 2, 3, 4, 5];

And we want to delete number 4, you can simply do the below code:

num.splice(num.indexOf(4), 1); //num will be [1, 2, 3, 5];

If you reusing this function, you write a reusable function which will be attached to Native array function like below:

Array.prototype.remove = Array.prototype.remove || function(x) {
  const i = this.indexOf(x);
  if(i===-1) return;
  this.splice(i, 1); //num.remove(5) === [1, 2, 3];
}

But how about if you are having the below array instead with few [5]s in the Array?

var num = [5, 6, 5, 4, 5, 1, 5];

We need a loop to check them all, but easier and more efficient way is using built-in JavaScript functions, so we write a function which use filter like below instead:

const _removeValue = (arr, x) => arr.filter(n => n!==x);
//_removeValue([1, 2, 3, 4, 5, 5, 6, 5], 5) //return [1, 2, 3, 4, 6]

Also there are third parties libraries which do help you to do this, like Lodash or Underscore, for more info look at lodash _.pull, _.pullAt or _.without.

@TheGwa 2017-05-11 12:28:30

There is a small typo. Please correct. this.splice(num.indexOf(x), 1); => this.splice(this.indexOf(x), 1);

@aikeru 2017-05-24 03:29:54

Please don't augment built-ins (attach functions to Array.prototype) in JavaScript. This is widely regarded as bad practice.

@Alireza 2017-05-25 08:45:07

I agree that's not the best thing to do in the world, but in this case how you could pass down it to the function?

@Richard Chan 2018-01-26 09:38:10

You should check the index. If index = -1, splice(-1,1) will remove the last element

@Gaurang Patel 2018-03-09 05:40:20

Very naive implementation would be as following:

Array.prototype.remove = function(data) {
    const dataIdx = this.indexOf(data)
    if(dataIdx >= 0) {
        this.splice(dataIdx ,1);
    }
    return this.length;
}

let a = [1,2,3];
// this will change arr a to [1, 3]
a.remove(2);

I return length of the array from the function to comply with the other methods like Array.prototype.push().

@Victor 2018-03-08 18:35:44

I just created a polyfill on the Array.prototype via Object.defineProperty to remove a desired element in an array without leading to errors when iterating over it later via for .. in ..

if (!Array.prototype.remove) {
  // Object.definedProperty is used here to avoid problems when iterating with "for .. in .." in Arrays
  // https://stackoverflow.com/questions/948358/adding-custom-functions-into-array-prototype
  Object.defineProperty(Array.prototype, 'remove', {
    value: function () {
      if (this == null) {
        throw new TypeError('Array.prototype.remove called on null or undefined')
      }

      for (var i = 0; i < arguments.length; i++) {
        if (typeof arguments[i] === 'object') {
          if (Object.keys(arguments[i]).length > 1) {
            throw new Error('This method does not support more than one key:value pair per object on the arguments')
          }
          var keyToCompare = Object.keys(arguments[i])[0]

          for (var j = 0; j < this.length; j++) {
            if (this[j][keyToCompare] === arguments[i][keyToCompare]) {
              this.splice(j, 1)
              break
            }
          }
        } else {
          var index = this.indexOf(arguments[i])
          if (index !== -1) {
            this.splice(index, 1)
          }
        }
      }
      return this
    }
  })
} else {
  var errorMessage = 'DANGER ALERT! Array.prototype.remove has already been defined on this browser. '
  errorMessage += 'This may lead to unwanted results when remove() is executed.'
  console.log(errorMessage)
}

Removing an integer value

var a = [1, 2, 3]
a.remove(2)
a // Output => [1, 3]

Removing a string value

var a = ['a', 'ab', 'abc']
a.remove('abc')
a // Output => ['a', 'ab']

Removing a boolean value

var a = [true, false, true]
a.remove(false)
a // Output => [true, true]

It is also possible to remove an object inside the array via this Array.prototype.remove method. You just need to specify the key => value of the Object you want to remove.

Removing an object value

var a = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 3, b: 2}]
a.remove({a: 1})
a // Output => [{a: 2, b: 2}, {a: 3, b: 2}]

@sujithklr93 2018-02-15 08:14:46

var array = [2, 5, 9];
array.splice(array.findIndex(x => x==5), 1);

Using Array.findindex, we can reduce the number of lines of code.

developer.mozilla.org

@pwilcox 2018-07-29 14:44:45

You better be sure you know the element is in the array, otherwise findindex returns -1 and consequently removes the 9.

@Lars Gyrup Brink Nielsen 2016-04-11 05:47:16

Vanilla JavaScript (ES5.1) – in place edition

Browser support: Internet Explorer 9 or later (detailed browser support)

/**
 * Removes all occurences of the item from the array.
 *
 * Modifies the array “in place”, i.e. the array passed as an argument
 * is modified as opposed to creating a new array. Also returns the modified
 * array for your convenience.
 */
function removeInPlace(array, item) {
    var foundIndex, fromIndex;

    // Look for the item (the item can have multiple indices)
    fromIndex = array.length - 1;
    foundIndex = array.lastIndexOf(item, fromIndex);

    while (foundIndex !== -1) {
        // Remove the item (in place)
        array.splice(foundIndex, 1);

        // Bookkeeping
        fromIndex = foundIndex - 1;
        foundIndex = array.lastIndexOf(item, fromIndex);
    }

    // Return the modified array
    return array;
}

Vanilla JavaScript (ES5.1) – immutable edition

Browser support: Same as vanilla JavaScript in place edition

/**
 * Removes all occurences of the item from the array.
 *
 * Returns a new array with all the items of the original array except
 * the specified item.
 */
function remove(array, item) {
    var arrayCopy;

    arrayCopy = array.slice();

    return removeInPlace(arrayCopy, item);
}

Vanilla ES6 – immutable edition

Browser support: Chrome 46, Edge 12, Firefox 16, Opera 37, Safari 8 (detailed browser support)

/**
 * Removes all occurences of the item from the array.
 *
 * Returns a new array with all the items of the original array except
 * the specified item.
 */
function remove(array, item) {
    // Copy the array
    array = [...array];

    // Look for the item (the item can have multiple indices)
    let fromIndex = array.length - 1;
    let foundIndex = array.lastIndexOf(item, fromIndex);

    while (foundIndex !== -1) {
        // Remove the item by generating a new array without it
        array = [
            ...array.slice(0, foundIndex),
            ...array.slice(foundIndex + 1),
        ];

        // Bookkeeping
        fromIndex = foundIndex - 1;
        foundIndex = array.lastIndexOf(item, fromIndex)
    }

    // Return the new array
    return array;
}

Related Questions

Sponsored Content

54 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

38 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

3 Answered Questions

41 Answered Questions

[SOLVED] Sort array of objects by string property value

33 Answered Questions

[SOLVED] For-each over an array in JavaScript?

12 Answered Questions

[SOLVED] How can I add new array elements at the beginning of an array in Javascript?

  • 2011-11-10 00:35:22
  • Moon
  • 689648 View
  • 1386 Score
  • 12 Answer
  • Tags:   javascript arrays

60 Answered Questions

[SOLVED] How can I merge properties of two JavaScript objects dynamically?

46 Answered Questions

39 Answered Questions

[SOLVED] Remove empty elements from an array in Javascript

Sponsored Content