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

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

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.

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

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

@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

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

@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, stringToRemoveFromArray is the string you want removed 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.

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

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

@nsantana 2017-05-12 02:00:54

Remove by Index

A function that returns a copy of array without the element at index:

/**
* removeByIndex
* @param {Array} array
* @param {Number} index
*/
function removeByIndex(array, index){
      return array.filter(function(elem, _index){
          return index != _index;
    });
}
l = [1,3,4,5,6,7];
console.log(removeByIndex(l, 1));

$> [ 1, 4, 5, 6, 7 ]

Remove by Value

Function that return a copy of array without the Value.

/**
* removeByValue
* @param {Array} array
* @param {Number} value
*/
function removeByValue(array, value){
      return array.filter(function(elem, _index){
          return value != elem;
    });
}
l = [1,3,4,5,6,7];
console.log(removeByValue(l, 5));

$> [ 1, 3, 4, 6, 7]

@Buffalo 2017-07-24 11:59:47

Are redundant constructions the norm around web developers? I have someone at work spraying stuff like this everywhere. Why not just return value != elem?!

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

OK, for example you have the array below:

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

And we want to delete number 4. You can simply use the below code:

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

If you are reusing this function, you write a reusable function which will be attached to the 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 have the below array instead with a few [5]s in the array?

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

We need a loop to check them all, but an easier and more efficient way is using built-in JavaScript functions, so we write a function which use a 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-party libraries which do help you to do this, like Lodash or Underscore. For more information, 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

@mpen 2017-04-09 20:09:01

Remove one value, using loose comparison, without mutating the original array, ES6

/**
 * Removes one instance of `value` from `array`, without mutating the original array. Uses loose comparison.
 *
 * @param {Array} array Array to remove value from
 * @param {*} value Value to remove
 * @returns {Array} Array with `value` removed
 */
export function arrayRemove(array, value) {
    for(let i=0; i<array.length; ++i) {
        if(array[i] == value) {
            let copy = [...array];
            copy.splice(i, 1);
            return copy;
        }
    }
    return array;
}

@darmis 2019-10-01 21:04:35

export const arrayRemove = (array, value) => [...array.filter(item => item !== value)]; Perhaps this could be simpler.

@mpen 2019-10-01 23:05:54

@darmis Simpler, yes, but doesn't do exactly the same thing. Also don't think you need the [... -- .filter should already return a copy.

@darmis 2019-10-02 07:21:04

@mpem My first impression was that could be a simpler way to do this but I agree is not doing the same thing. And yes the [... it is not needed in this case so even simpler :) thanks for that.

@Ali Akram 2017-03-20 11:16:57

I made a function:

function pop(valuetoremove, myarray) {
    var indexofmyvalue = myarray.indexOf(valuetoremove);
    myarray.splice(indexofmyvalue, 1);
}

And used it like this:

pop(valuetoremove, myarray);

@Jamiec 2017-03-28 14:06:10

If you're going to name it pop at least make it do what the method name implies!

@Stelios Voskos 2016-11-29 20:54:38

While most of the previous answers answer the question, it is not clear enough why the slice() method has not been used. Yes, filter() meets the immutability criteria, but how about doing the following shorter equivalent?

const myArray = [1,2,3,4];

And now let’s say that we should remove the second element from the array, we can simply do:

const newArray = myArray.slice(0, 1).concat(myArray.slice(2, 4));

// [1,3,4]

This way of deleting an element from an array is strongly encouraged today in the community due to its simple and immutable nature. In general, methods which cause mutation should be avoided. For example, you are encouraged to replace push() with concat() and splice() with slice().

@rncrtr 2015-01-07 19:53:17

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;

Related Questions

Sponsored Content

41 Answered Questions

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

43 Answered Questions

[SOLVED] Sort array of objects by string property value

41 Answered Questions

[SOLVED] Remove empty elements from an array in Javascript

86 Answered Questions

[SOLVED] How do JavaScript closures work?

60 Answered Questions

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

47 Answered Questions

3 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
  • 748034 View
  • 1480 Score
  • 13 Answer
  • Tags:   javascript arrays

33 Answered Questions

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

55 Answered Questions

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

Sponsored Content