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 - frameworks are not allowed.

30 comments

@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

@vikramvi 2019-07-11 05:48:31

Refer to answer from @ujeenator, it has more optimal way of doing action

@pritam 2019-10-02 06:24:31

In strict mode, delete wouldn't work.

@Ravi Makwana 2020-01-09 09:54:49

I found this BLOG which is showing 9 ways to do it

9 Ways to Remove Elements From A JavaScript Array - Plus How to Safely Clear JavaScript Arrays

I prefer to use filter()

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

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

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

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

const array = [2, 5, 9];

console.log(array);

const 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.

@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.

@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 Liesis 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]; ?

@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.

@Alex 2017-10-14 04:28:57

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

@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?

@Christos Karapapas 2019-10-20 07:45:32

Splice is not working as expected if your array contains elements with negative indices.

@Arun s 2019-12-27 10:58:34

You can use splice to remove objects or values from array. Lets consider an array of length 5 with values 10,20,30,40,50 and i want to remove the value 30 from it.

var array = [10,20,30,40,50];
if (array.indexOf(30) > -1) {
  array.splice(array.indexOf(30), 1);
}
console.log(array); // [10,20,40,50]

@Ketan Ramteke 2019-12-24 13:59:43

Array.prototype.filter() can do the job. example:

let newArr= [1, 2, 3, 4, 5, 6];

removeNum = numToBeRemoved => arr.filter(num => num != numToBeRemoved);

removeNum(5);

OUTPUT:  [1, 2, 3, 4, 6]

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

Removing a particular element/string from an array can be done in a one-liner:

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

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

NOTE One comment brought a very good point

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

Its always good practice to check if the element exists in your array first, before removing it.

if (theArray.indexOf("stringToRemoveFromArray") >= 0){
   theArray.splice(theArray.indexOf("stringToRemoveFromArray"), 1);
}

If you have access to newer Ecmascript versions on your client's computers (WARNING, may not work on older stations):

var array=['1','2','3','4','5','6']
var newArray = array.filter((value)=>value!='3');

Where '3' is the value you want removed from the array. The array would then become : ['1','2','4','5','6']

@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.

@Josh 2019-12-19 09:05:46

Remove a specific element from an array can be done in one line with the filter option, and it's supported by all browsers: https://caniuse.com/#search=filter%20array

function removeValueFromArray(array, value) {
    return array.filter(e => e != value)
}

I tested this function here: https://bit.dev/joshk/jotils/remove-value-from-array/~code#test.ts

@Kamil Kiełczewski 2019-12-09 16:04:13

Performance

Today 09.12.2019 I conduct performance tests on MacOs HighSierra 10.13.6 for chosen solutions. I show delete (A) but I not use it in comparison with other methods because it left empty space in array.

The conclusions

  • the fastest solution is array.splice (C) (except safari for small array where it has second time)
  • for big arrays array.slice+splice (H) is fastest immutable solution for firefox and safari; Array.from (B) is fastest in chrome
  • mutable solution are usually 1.5x-6x faster than immutable
  • for small tables on safari, surprisingly mutable solution (C) is slower than immutable solution (G)

Details

In tests I remove middle element from array in different ways. The A, C solutions are in-place. The B, D, E, F, G, H solutions are immutable.

Results for array with 10 elements

enter image description here

It chrome the array.splice (C) is fastest in-place solution. The array.filter (D) fastest immutable solution. The slowest is array.slice (F). You can perform test on your machine here.

Results for array with 1.000.000 elements

enter image description here

It chrome the array.splice (C) is fastest in-place solution (the delete (C) is similar fast - but it left empty slot in array (so it not perform 'full remove')). The array.slice-splice (H) is fastest immutable solution. The slowest is array.filter (D and E). You can perform test on your machine here.

var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var log = (letter,array) => console.log(letter, array.join `,`);

function A(array) {
  var index = array.indexOf(5);
  delete array[index];
  log('A', array);
}

function B(array) {
  var index = array.indexOf(5);
  var arr = Array.from(array);
  arr.splice(index, 1)
  log('B', arr);
}

function C(array) {
  var index = array.indexOf(5);
  array.splice(index, 1);
  log('C', array);
}

function D(array) {
  var arr = array.filter(item => item !== 5)
  log('D', arr);
}

function E(array) {
  var index = array.indexOf(5);
  var arr = array.filter((item, i) => i !== index)
  log('E', arr);
}

function F(array) {
  var index = array.indexOf(5);
  var arr = array.slice(0, index).concat(array.slice(index + 1))
  log('F', arr);
}

function G(array) {
  var index = array.indexOf(5);
  var arr = [...array.slice(0, index), ...array.slice(index + 1)]
  log('G', arr);
}

function H(array) {
  var index = array.indexOf(5);
  var arr = array.slice(0);
  arr.splice(index, 1);
  log('H', arr);
}

A([...a]);
B([...a]);
C([...a]);
D([...a]);
E([...a]);
F([...a]);
G([...a]);
H([...a]);
This snippet only presents code used in performance tests - it not perform tests itself.

Comparison for browsers: Chrome v78.0.0, Safari v13.0.4 and Firefox v71.0.0

enter image description here

@Taylor Hawkes 2019-11-06 20:25:28

To find and remove a particular string from an array of strings:

var colors = ["red","blue","car","green"];
var carIndex = colors.indexOf("car");//get  "car" index
//remove car from the colors array
colors.splice(carIndex, 1); // colors = ["red","blue","green"]

Source: https://www.codegrepper.com/?search_term=remove+a+particular+element+from+array

@Ajay Thakur 2019-11-04 05:10:50

You can create a prototype for that. Just pass the array element and the value which you want to remove from the array element

Array.prototype.removeItem = function(array,val){
	array.forEach((arrayItem,index)=>{
		if(arrayItem==val){
			array.splice(index,1);
		}
	});
	return array;
}
var DummyArray = [1,2,3,4,5,6];
console.log(DummyArray.removeItem(DummyArray,3));

@Vinod Kumar 2019-10-14 08:38:44

Remove the particular array item

enter image description here

var cars = ["Apple", "Banana", "Mango", "Orange", "Grapes"];

document.getElementById("demo").innerHTML = cars;

for( var i = 0; i < cars.length; i++){ 
   if ( cars[i] === "Banana") {
     cars.splice(i, 1); 
     i--;
   }
}

document.getElementById("demo2").innerHTML =  cars;
p {
  font-size: 20px; 
  padding: 10px; 
  border: 1px dashed tan;
  color: brown;
}
<!DOCTYPE html>
<html>
<body>

<h2>Before</h2>
<p id="demo"></p>
<h2>After</h2>
<p id="demo2"></p>
</body>
</html>

@pritam 2019-10-02 07:36:39

Most of the answers here give a solution using -

  1. indexOf and splice
  2. delete
  3. filter
  4. regular for loop

Although all the solutions should work with these methods, I thought we could use string manipulation.

Points to note about this solution -

  1. It will leave holes in the data. (could be removed with extra filter)
  2. This solution works for not just primitive search values but also objects.

The trick is to -

  1. stringify input data set and the search value
  2. replace the search value in the input data set with empty string
  3. return split data on delimiter ,.
    remove = (input, value) => {
        const stringVal = JSON.stringify(value);
        const result = JSON.stringify(input)

        return result.replace(stringVal, "").split(",");
    }

A JS fiddle with tests for objects and numbers is created here - https://jsfiddle.net/4t7zhkce/33/

Check the remove method in the fiddle.

@rajat44 2016-10-04 08:07:50

You can use ES6. For example to delete the value '3' in this case:

var array=['1','2','3','4','5','6']
var newArray = array.filter((value)=>value!='3');
console.log(newArray);

Output :

["1", "2", "4", "5", "6"]

@Claudio Holanda 2017-03-16 15:27:40

This answer is nice because it creates a copy of the original array, instead of modifying the original directly.

@Chang 2019-01-27 19:45:05

Note: Array.prototype.filter is ECMAScript 5.1 (No IE8). for more specific solutions: stackoverflow.com/a/54390552/8958729

@Samer Murad 2019-12-06 11:31:04

a very elegant way to keep immutability of the array... and I HATE the splice method! take my upvote

@Amin Adel 2019-12-16 15:24:17

perfect answer.

@Yohannes Kristiawan 2019-09-18 10:57:57

I would like to suggest to remove one array item using delete and filter:

var arr = [1,2,3,4,5,5,6,7,8,9];
delete arr[5];
arr = arr.filter(function(item){ return item != undefined; });
//result: [1,2,3,4,5,6,7,8,9]

So, we can remove only one specific array item instead of all items with the same value.

@Kinslert Virguez. 2019-09-17 22:49:59

you can create an index with all accesors example

<div >
</div>

function getIndex($id){
  return (
  this.removeIndex($id)
  alert("This element was removed")
  )
}


function removeIndex(){
   const index = $id; 
   this.accesor.id.splice(index.id) // you can use splice for slice index on accesor id and return with message
}
<div>
<fromList>
  <ul>
{...this.array.map( accesors => {
    <li type="hidden"></li>
    <li>{...accesors}</li>
}) 

}
  </ul>
</fromList>

<form id="form" method="post">
<input  id="{this.accesors.id}">
<input type="submit" callbackforApplySend...getIndex({this.accesors.id}) name="sendendform" value="removeIndex" >
</form>

</div>

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

Take profit of reduce method as follows:

Case a) if you need to remove an element by index:

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

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

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

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

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

You have 1 to 9 in the array, and you want remove 5. Use the 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 values. Example:- 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, 1,7 and 8 removed", newNumberArray);


If you want to remove an array value in an array. Example: [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.

@mekbib.awoke 2019-08-23 12:20:13

You can extend the array object to define a custom delete function as follows:

let numbers = [1,2,4,4,5,3,45,9];

numbers.delete = function(value){
    var indexOfTarget = this.indexOf(value)

    if(indexOfTarget !== -1)
    {
        console.log("array before delete " + this)
        this.splice(indexOfTarget, 1)
        console.log("array after delete " + this)
    }
    else{
        console.error("element " + value + " not found")
    }
}
numbers.delete(888)
// Expected output:
// element 888 not found
numbers.delete(1)

// Expected output;
// array before delete 1,2,4,4,5,3,45,9
// array after delete 2,4,4,5,3,45,9

@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.

@MHOOS 2019-06-20 09:47:31

@codepleb, can you elaborate on why you prefer filter over splice and why you think filter is more readable?

@eightyfive 2019-06-20 10:07:26

Albeit not recommended for lengthy arrays.

@codepleb 2019-06-26 16:12:23

@MHOOS Slice has a lot of options and they are confusing IMHO. You can, if you want, pass a start and end variable and while the start index is included, the end index is not, etc. It's harder to read code playing with slice. If you don't use that too often, you often end up checking the docs during reviews to check if something is correct. Docs: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

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

Splice, filter and delete to remove an element from an array

Every array has its index, and it helps to delete a particular element with their index.

The splice() method

array.splice(index, 1);

The first parameter is index and the second is the number of elements you want to delete from that index.

So for a single element, we use 1.

The delete method

delete array[index]

The filter() method

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

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

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

@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

The index at which to start changing the array (with origin 0). If greater than the length of the array, the actual starting index will be set to the length of the array. If negative, it will begin that many elements from the end of the array (with origin -1) and will be set to 0 if the 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 references, kindly go through:

Array.prototype.splice()

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

To remove a 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 the 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);
        }
    }
    
  4. 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'?

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

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

@Ole 2019-08-04 20:02:53

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

I want to answer based on ECMAScript 6. Assume, you have an array like below:

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

If you want to delete at a special index like 2, write the below code:

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

But if you want to 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.

@AmerllicA 2020-01-16 13:29:35

Dear @PeterMortensen, Thanks for your great edition.

@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.

@Phil 2019-09-18 05:18:23

OP asked about removing a particular (one) element from an array. This function does not terminate when one element is found but keeps comparing every single element in the array until the end is reached.

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

@mekbib.awoke 2019-08-23 12:23:56

this may collide with other code, libraries, i would rather implement a remove function for that specific array

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

Delete an element from last

arrName.pop();

Delete an element from first

arrName.shift();

Delete from the middle

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

Example: arrName.splice(1, 1);

Delete one element from last

arrName.splice(-1);

Delete by using an array index number

 delete arrName[1];

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

Define a method named remove() on array objects using the prototyping 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 the first item found in the array
    var index = this.indexOf(item);

    if (index > -1) {
        // The splice() method is used to add/remove items(s) in the 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: The below is the full example code executed on the 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 beginning 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 (temporarily) 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
>

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

A very naive implementation would be as follows:

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 the length of the array from the function to comply with the other methods, like Array.prototype.push().

@Adeel Imran 2017-12-26 19:32:06

You should never mutate your array. As this is against the functional programming pattern. You can create a new array without referencing the array you want to change data of using the ECMAScript 6 method filter;

var myArray = [1, 2, 3, 4, 5, 6];

Suppose you want to remove 5 from the array, you can simply do it like this:

myArray = myArray.filter(value => value !== 5);

This will give you a new array without the value you wanted to remove. So the result will be:

 [1, 2, 3, 4, 6]; // 5 has been removed from this array

For further understanding you can read the MDN documentation on Array.filter.

Related Questions

Sponsored Content

48 Answered Questions

13 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
  • 759649 View
  • 1502 Score
  • 13 Answer
  • Tags:   javascript arrays

63 Answered Questions

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

42 Answered Questions

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

56 Answered Questions

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

44 Answered Questions

[SOLVED] Sort array of objects by string property value

37 Answered Questions

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

86 Answered Questions

[SOLVED] How do JavaScript closures work?

41 Answered Questions

[SOLVED] Remove empty elements from an array in Javascript

4 Answered Questions

Sponsored Content