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

6 551

1 047

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

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

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

Walker

Posted 2011-04-23T22:17:18.487

Reputation: 36 128

82

If you need to support <IE9 (sigh) then check this SO question regarding indexOf in IE.

– Scotty.NET – 2013-09-13T07:48:49.520

21

(lodash) array = ['a', 'b', 'c']; _.pull(array, 'a') // array => ['b', 'c']; See also http://stackoverflow.com/questions/5767325/remove-a-specific-element-from-an-array-in-javascript/32212535#32212535

– Chun Yang – 2015-08-25T20:28:43.343

7filter method can do what you want. – Salvador Dali – 2015-09-05T23:43:21.700

5You can use delete but it will not rearange the index instead it will set this slot to 'undefined × 1'. For example: var list = [1,2,3,4,5,6] -> delete list[1] -> [1, undefined × 1, 3, 4, 5, 6]. – DevWL – 2016-05-24T23:26:45.157

3delete should be more performant in the short term, because it won't have to shift the later items. forEach, map and filter will automatically skip processing for undefined (deleted) items. But it's probably not ideal if you will be adding a lot of things to your array in future, or reading it many times. – joeytwiddle – 2016-07-29T08:55:01.323

6

Here a performance benchmark of the two major possibilities: http://jsben.ch/#/b4Ume

– EscapeNetscape – 2017-03-03T16:46:45.783

Answers

9 483

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.


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

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

Array.prototype.indexOf || (Array.prototype.indexOf = function(d, e) {
    var a;
    if (null == this) throw new TypeError('"this" is null or not defined');
    var c = Object(this),
        b = c.length >>> 0;
    if (0 === b) return -1;
    a = +e || 0;
    Infinity === Math.abs(a) && (a = 0);
    if (a >= b) return -1;
    for (a = Math.max(0 <= a ? a : b - Math.abs(a), 0); a < b;) {
        if (a in c && c[a] === d) return a;
        a++
    }
    return -1
});

Tom Wadley

Posted 2011-04-23T22:17:18.487

Reputation: 95 954

4

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-02T02:33:52.417

4It’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. – zykadelic – 2013-03-07T21:50:54.357

175Dangerous! 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. – Adrian P. – 2013-09-06T16:44:17.573

5Does splice preserve the array order?? – Alexandre Wiechers Vaz – 2013-09-26T18:18:20.933

15@AlexandreWiechersVaz Of course it preserves order, if it didn't then it would be absolutely worthless – TheZ – 2013-12-11T19:18:02.937

10

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

– None – 2014-06-08T10:42:27.953

5indexOf 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... – Chris – 2014-07-07T14:00:23.237

5

Related question: How to do it with jQuery (jQuery.grep). http://stackoverflow.com/questions/3596089/how-to-remove-specifc-value-from-array-using-jquery

– Curtis Yallop – 2014-07-31T23:20:49.323

7@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. – Adrian P. – 2015-01-19T13:51:48.400

9@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. – UpTheCreek – 2015-01-19T15:47:21.453

5

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

– CodyBugstein – 2015-01-29T12:52:13.660

6

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: http://jsfiddle.net/b0e7zsm3/

– aroth – 2015-02-06T01:53:13.140

7

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

– klenium – 2015-08-25T19:52:56.563

2

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 (https://jsbin.com/xufovopoji/edit?html,js,output)

– Thaenor – 2015-10-18T15:20:04.663

6

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." http://stackoverflow.com/a/9882349/922522

– Justin – 2015-12-14T20:02:28.093

6

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! https://support.microsoft.com/en-us/lifecycle/search?sort=PN&alpha=internet%20explorer&Filter=FilterNO

– Lukas – 2016-01-13T08:08:26.517

3Why not use delete method directly like delete arname [index]; ? – Chinmaya B – 2016-02-14T15:38:48.680

1

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

– Tommy Steimel – 2016-04-11T18:27:15.853

@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. – vard – 2016-04-26T14:30:27.630

1Can anyone explain how the polyfill actually works? Code looks very interesting. You're comparing infinity (observing variable type) to Math.abs(a) &amp;&amp; (a = 0) and doing some incredible other stuff involving &gt;&gt;&gt;? – Popey Gilbert – 2016-06-10T22:43:54.823

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-12T03:42:06.543

Update: i found this post http://stackoverflow.com/questions/8173210/delete-vs-splice-on-associative-array. and now i know the difference of splice and delete.

– John Christian De Chavez – 2016-07-12T04:03:18.090

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 =&gt; e.property).indexOf(PROPERTY_VALUE_TO_SEARCH) if your browser supports Arrow Functons. – K._ – 2016-09-04T14:04:59.157

10

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

– Tom Wadley – 2011-04-23T22:28:10.463

As @klenium said, the splice() method changes the content of an array, it does not return a new array. – Aykut Yaman – 2017-01-11T15:22:15.077

2arr = [1,2,3,4,5] var filtered = arr.filter(function(ele){ return ele != 3; }); //filtered = [1,2,4,5]; – Sarath S Nair – 2017-01-30T04:26:31.200

1OPs provided spec does not specify an array of unique integers. indexOf will only return the position of the first found match (from optional "fromIndex"). – Greg – 2017-03-06T16:27:17.053

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. – heringer – 2017-05-04T12:30:57.970

1

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

– iulial – 2017-06-28T13:53:26.493

Wont it shift array Index to lower level and subsequent element wont be available in list if we are looping through an array. – Megh – 2017-09-26T18:31:05.310

Splice is the best, with delete my JSON.stringify has a null on place that deleted – Marcelo Rafael – 2017-10-14T04:28:57.087

use array.filter() is the best way – HamidReza Heydari – 2017-12-16T08:59:01.907

@TomWadley why the first if condition is (index > -1) instead of (index != -1) ? – MrClan – 2018-01-08T09:40:13.287

1@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 &gt; -1. – Tom Wadley – 2018-01-11T16:48:28.573

963

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

Peter Olson

Posted 2011-04-23T22:17:18.487

Reputation: 78 416

250delete is not the correct way to remove an element from an array! – Felix Kling – 2013-01-27T15:30:48.417

55@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. – Peter Olson – 2013-01-27T15:36:52.527

75delete will not update the length of the array neither really erases the element, only replaces it with the special value undefined. – diosney – 2013-02-17T03:44:59.937

29@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. – Peter Olson – 2013-04-15T19:13:42.207

5for(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]) – Bambax – 2013-05-23T18:04:43.963

3Splice 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. – Pingwin Tux – 2014-03-13T09:17:27.407

8delete is a good mechanism if you are dealing with named properties var array=[];array['red']=1;array['green']=2;array['blue']=3;delete array['green']; – Jefferey Cave – 2014-10-21T23:00:59.710

@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. – Eric Elliott – 2014-11-20T00:35:22.987

in modern js engines, using: array[i] = null is favored instead of delete array[i] – BenG – 2015-08-17T15:20:35.457

1@BenG, can you provide a reference or two for that statement, or at least explain why it's favored? – Paul – 2015-08-19T12:03:07.840

2@BenG That doesn't make sense: they do different things, how can one be favored? – Peter Olson – 2015-08-19T23:09:51.030

2

@Paul it's referenced many places(e.g. http://www.smashingmagazine.com/2012/11/writing-fast-memory-efficient-javascript/#de-referencing-misconceptions). 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

– BenG – 2015-08-21T14:50:27.870

@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)... – Sandy Gifford – 2018-01-26T20:15:17.797

Indexed for loop wouldn't work for all arrays. If you previously used delete on the array, then for loop will crash. – Sasa – 2018-05-15T09:13:39.690

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. – Grant Gryczan – 2018-06-09T05:28:16.240

3@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. – Peter Olson – 2018-06-11T18:15:01.003

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. – Grant Gryczan – 2018-06-12T00:51:37.467

4@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. – Peter Olson – 2018-06-12T02:27:51.190

775

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

Ujeenator

Posted 2011-04-23T22:17:18.487

Reputation: 8 890

4but, sometimes we want to remove element from original array(non immutable), for example array used in Angular 2 *ngFor directive – Ravinder Payal – 2017-02-08T14:06:04.300

22Better than the accepted solution because it does not assume only one occurrence of a match and immutability is preferable – Greg – 2017-03-06T16:46:21.100

3Using filter is so much nicer than using splice. Too simple. – user3344977 – 2017-03-17T22:22:49.710

6filter must be much slower for a big array though? – Nathan – 2017-07-17T01:02:59.850

What's the point of immutability mentioned if you used assignment of the same variable in your examples? :) – mench – 2017-08-19T11:36:51.273

@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. – Ujeenator – 2017-08-19T12:10:30.990

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 =&gt; el !==3) will result on no modification on arr2, while doing the splice, both arrays will be modified. – Soldeplata Saketos – 2017-08-28T07:31:58.043

1Super slow method. – highmaintenance – 2017-12-12T13:05:30.883

@Andy in comparison to what method and what scenario? – Ujeenator – 2017-12-12T15:00:41.573

@Nathan in comparison to what method and what scenario? By slower you mean execution time? – Ujeenator – 2017-12-12T15:01:54.787

@Ujeenator filter is super slow if you need to remove a single element from an array – highmaintenance – 2017-12-12T16:42:01.607

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 =&gt; num == 3) it will remove both values of 3 – tomaytotomato – 2018-03-26T20:23:48.687

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

– Greg – 2018-04-05T20:32:10.710

I love the reasoning behind this answer. Remove items by filtering out the ones you don't want. Brilliant! – Stephen – 2018-05-28T17:23:38.490

1This 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)=&gt;i!==2) – Matthew – 2018-08-15T12:50:44.643

376

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

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

delete array[ index ];

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

array.splice( index, 1 );

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

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

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

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

xavierm02

Posted 2011-04-23T22:17:18.487

Reputation: 5 463

46It's worth noting that var value will not store the removed value but an array containing the removed value. – Jakub – 2013-07-10T09:55:45.950

19delete is not the correct way to remove an element from an array!! – Progo – 2014-07-04T14:20:43.760

13If you want to "empty a slot", use array[index] = undefined;. Using delete will destroy optimisation. – Bergi – 2014-08-11T16:40:29.990

3@Jakub very good comment because to understand that I lost much time and thought my application code is somehow broken... – Pascal – 2014-12-14T19:14:58.747

244

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.

Ben Lesh

Posted 2011-04-23T22:17:18.487

Reputation: 95 488

8@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. – gabeno – 2014-01-29T20:06:34.327

1Second function is rather inefficient. On every iteration "indexOf" will start search from beginning of array. – Ujeenator – 2015-02-25T13:32:12.057

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

– Ben Lesh – 2015-03-03T03:12:31.477

@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-29T18:01:15.573

1@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. – Eugene Kuzmenko – 2015-03-30T09:37:04.597

1@AlJey, it's available only from IE9+. There is still a chance that it wouldn't work. – Ujeenator – 2015-03-30T16:23:56.160

@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. – Eugene Kuzmenko – 2015-03-30T18:05:20.393

1This 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. – mintedsky – 2015-07-14T23:39:58.733

138

There are two major approaches:

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

  2. delete: delete anArray[index];

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

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

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

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

Sasa

Posted 2011-04-23T22:17:18.487

Reputation: 2 090

112

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

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

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

rooms = rooms.remByVal('hello')

console.log(rooms)

Zirak

Posted 2011-04-23T22:17:18.487

Reputation: 26 086

10

Bad idea, see this post: http://stackoverflow.com/questions/948358/array-prototype-problem

– MMeah – 2012-07-09T22:10:08.007

9If you're doing a for in on an array, you already have a problem. – Zirak – 2014-05-14T13:01:58.757

13I'm not a big fan of this approach. If you end up using different libraries or frameworks, they can end up conflicting with each other. – Charlie Kilian – 2011-04-23T22:30:15.173

This worked as well, I chose to go with the indexOf function in the end though. Thanks for the help! – Walker – 2011-04-23T22:35:58.207

1if you do for in on arrays, you already have bigger problems. – Rainb – 2018-08-01T06:20:21.497

use Object.defineProperty https://stackoverflow.com/a/35518127/3779853 and you're good to go.

– Blauhirn – 2018-09-20T19:02:20.027

86

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

Find and move (move):

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

Use indexOf and splice (indexof):

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

Use only splice (splice):

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

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

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

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

Remove first occurrence:
    move_one 0.0041 ms
    indexof_one 0.0021 ms

slosd

Posted 2011-04-23T22:17:18.487

Reputation: 1 812

3Looks like the 'move' method presented here should work in all browsers, and also avoids creating an extra array; most other solutions here have one or both of these problems. I think this one deserves a lot more votes, even if it doesn't look as "pretty". – sockmonk – 2015-07-29T11:50:21.873

58

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

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

Usage

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

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

Definition

var helper = {

    // Remove and return the first occurrence     

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

    // Remove and return all occurrences  

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

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

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

            i++;                
        }

        return removed;
    }
};

amd

Posted 2011-04-23T22:17:18.487

Reputation: 13 521

I don't know that you need the -1 check (i > -1). Also, I think these functions act more like filter than remove. If you pass row.id === 5, it will result in an array with only id 5, so it is doing the opposite of remove. It would look nice in ES2015: var result = ArrayHelper.remove(myArray, row => row.id === 5); – What Would Be Cool – 2015-09-20T19:42:45.147

@WhatWouldBeCool this function modify the original array, and return the removed item instead of copying the result to a new array – amd – 2015-09-21T07:21:13.103

55

John Resig posted a good implementation:

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

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

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

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

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

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

myArray.remove(8);

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

Roger

Posted 2011-04-23T22:17:18.487

Reputation: 948

Just learned by the hard way why it is a good idea to use Object.prototype.hasOwnProperty always ¬¬ – Davi Fiamenghi – 2015-04-11T04:58:05.480

53

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

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

_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); // => [2, 3, 4]

vatsal

Posted 2011-04-23T22:17:18.487

Reputation: 2 705

52

You can do it easily with filter method:

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

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

Salvador Dali

Posted 2011-04-23T22:17:18.487

Reputation: 109 137

Nice solution but I see one problem and that is it creates new array and doesn't do anything to original array. – Mak – 2014-02-22T23:14:06.837

@Mak you are correct. This indeed creates another array. But if you do not want to do this you can overwrite old one with a new one. – Salvador Dali – 2014-02-22T23:17:51.250

3Also note, Array.prototype.filter is ECMAScript 5.1 (No IE8) – Montana Harkin – 2014-05-23T20:35:33.090

1Do you have a source on that this is faster? – user3711421 – 2017-07-28T18:21:57.593

Nice solution. But as you point out, but important to make bald, it does not produce the same result as slice and indexOf since it will remove all occurrences of 1 – user3711421 – 2017-07-28T18:28:36.473

@user3711421 this is because just slice and indexOf does not do what he wants "to remove a specific element". It removes the element only once, this remove a specific element no matter how many of them do you have – Salvador Dali – 2017-07-28T20:05:09.010

40

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

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

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

Loupax

Posted 2011-04-23T22:17:18.487

Reputation: 2 225

37

You can use ES6.

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

Output :

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

rajat44

Posted 2011-04-23T22:17:18.487

Reputation: 1 493

34

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

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

Call this function

remove_item(array,value);

Ekramul Hoque

Posted 2011-04-23T22:17:18.487

Reputation: 3 282

3@RolandIllig Except the use of a for in-loop and the fact that the script could stopped earlier, by returning the result from the loop directly. The upvotes
are reasonable ;)
– yckart – 2014-12-30T16:13:41.180

This is an excellent approach for small arrays. It works in every browser, uses minimal and intuitive code, and without any extra complex frameworks, shims, or polyfills. – Beejor – 2016-08-21T23:12:41.537

I should also reiterate yckart's comment that for( i = 0; i &lt; arr.length; i++ ) would be a better approach since it preserves the exact indices versus whatever order the browser decides to store the items (with for in). Doing so also lets you get the array index of a value if you need it. – Beejor – 2016-08-21T23:20:39.577

32

You can use lodash _.pull (mutate array), _.pullAt (mutate array) or _.without (does't mutate array),

var array1 = ['a', 'b', 'c', 'd']
_.pull(array1, 'c')
console.log(array1) // ['a', 'b', 'd']

var array2 = ['e', 'f', 'g', 'h']
_.pullAt(array2, 0)
console.log(array2) // ['f', 'g', 'h']

var array3 = ['i', 'j', 'k', 'l']
var newArray = _.without(array3, 'i') // ['j', 'k', 'l']
console.log(array3) // ['i', 'j', 'k', 'l']

Chun Yang

Posted 2011-04-23T22:17:18.487

Reputation: 1 496

1That's not core JS as the OP requested, is it? – some-non-descript-user – 2015-09-24T21:01:50.303

9@some-non-descript-user You are right. But a lot of users like me come here looking for a general answer not just for the OP only. – Chun Yang – 2015-10-01T03:38:30.253

@ChunYang You are absolutely right. I am already using lodash, why not just use it if it saves time. – int-i – 2018-06-08T21:48:30.703

31

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.

Alireza

Posted 2011-04-23T22:17:18.487

Reputation: 43 514

27

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

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

Then when I want to use it:

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

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

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

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

sofiax

Posted 2011-04-23T22:17:18.487

Reputation: 289

23

ES6 & without mutation: (October 2016)

const removeByIndex = (list, index) =>
  [
    ...list.slice(0, index),
    ...list.slice(index + 1)
  ];

Then :

removeByIndex([33,22,11,44],1) //=> [33,11,44]

Abdennour TOUMI

Posted 2011-04-23T22:17:18.487

Reputation: 31 941

21

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


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

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

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

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

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

    return destroyed;
}

Usage:

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

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

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

x.destroy(3);         // => null
x;                    // => [1, 2]

zykadelic

Posted 2011-04-23T22:17:18.487

Reputation: 697

20

If you have complex objects in the array you can use filters? In situations where $.inArray or array.splice is not as easy to use. Especially if the objects are perhaps shallow in the array.

E.g. if you have an object with an Id field and you want the object removed from an array:

this.array = this.array.filter(function(element, i) {
    return element.id !== idToRemove;
});

flurdy

Posted 2011-04-23T22:17:18.487

Reputation: 2 487

This is how I like to do it. Using an arrow function it can be a one-liner. I'm curious about performance. Also worth nothing that this replaces the array. Any code with a reference to the old array will not notice the change. – joeytwiddle – 2016-07-29T08:50:36.683

19

You should never mutate your array your array. As this is against functional programming pattern. What you can do is create a new array without referencing the array you want to change data of using es6 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 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Adeel Imran

Posted 2011-04-23T22:17:18.487

Reputation: 2 614

19

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-1).concat(items.slice(i, 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/)

Flavio Copes

Posted 2011-04-23T22:17:18.487

Reputation: 1 569

18

A more modern, ECMAScript 2015 (formerly known as Harmony or ES 6) approach. Given:

const items = [1, 2, 3, 4];
const index = 2;

Then:

items.filter((x, i) => i !== index);

Yielding:

[1, 2, 4]

You can use Babel and a polyfill service to ensure this is well supported across browsers.

bjfletcher

Posted 2011-04-23T22:17:18.487

Reputation: 7 791

16

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

Stand-alone function

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

    if(index === -1) return;

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

Prototype method

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

    if(index === -1) return;

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

wharding28

Posted 2011-04-23T22:17:18.487

Reputation: 815

Just a note, 1 caveat with this method is the potential for stack overflows. Unless you're working with massive arrays, you shouldn't have an issue. – wharding28 – 2015-09-08T05:57:20.920

15

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

Aram Grigoryan

Posted 2011-04-23T22:17:18.487

Reputation: 649

14

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

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

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

Live Demo

Jeff Noel

Posted 2011-04-23T22:17:18.487

Reputation: 5 551

14

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!

Ardi

Posted 2011-04-23T22:17:18.487

Reputation: 240

13

  Array.prototype.removeItem = function(a) {
            for (i = 0; i < this.length; i++) {
                if (this[i] == a) {
                    for (i2 = i; i2 < this.length - 1; i2++) {
                        this[i2] = this[i2 + 1];
                    }
                    this.length = this.length - 1
                    return;
                }
            }
        }

    var recentMovies = ['Iron Man', 'Batman', 'Superman', 'Spiderman'];
    recentMovies.removeItem('Superman');

Don Vincent Preziosi

Posted 2011-04-23T22:17:18.487

Reputation: 137

13

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

Thilina Sampath

Posted 2011-04-23T22:17:18.487

Reputation: 1 442

12

Remove by Index

Function that return 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]

nsantana

Posted 2011-04-23T22:17:18.487

Reputation: 811

11

Create new array:

var my_array = new Array();

Add elements to this array:

my_array.push("element1");

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

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

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

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

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

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

Remove 1 element located at index from the array

my_array.splice(index, 1);

Enrico

Posted 2011-04-23T22:17:18.487

Reputation: 405

10

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

var index = jQuery.inArray(val,arr);
if (index > -1) {
    arr.splice(index, 1);
    //console.log(arr);
}

NullPointer

Posted 2011-04-23T22:17:18.487

Reputation: 1 955

jQuery is always good for taking care of any cross-browser compatibility issues of the different JavaScript APIs. – Henry Heleine – 2014-12-09T22:15:23.940

9

I think many of the JavaScript instructions are not well thought out for functional programming. Splice returns the deleted element where most of the time you need the reduced array. This is bad.

Imagine you are doing a recursive call and have to pass an array with one less item, probably without the current indexed item. Or imagine you are doing another recursive call and has to pass an array with an element pushed.

In neither of these cases you can do myRecursiveFunction(myArr.push(c)) or myRecursiveFunction(myArr.splice(i,1)). The first idiot will in fact pass the length of the array and the second idiot will pass the deleted element as a parameter.

So what I do in fact... For deleting an array element and passing the resulting to a function as a parameter at the same time I do as follows

myRecursiveFunction(myArr.slice(0,i).concat(a.slice(i+1)))

When it comes to push that's more silly... I do like,

myRecursiveFunction((myArr.push(c),myArr))

I believe in a proper functional language a method mutating the object it's called upon must return a reference to the very object as a result.

Redu

Posted 2011-04-23T22:17:18.487

Reputation: 12 471

9

2017-05-08

Most of the given answers work for strict comparison, meaning that both objects reference the exact same object in memory (or are primitive types), but often you want to remove a non-primitive object from an array that has a certain value. For instance, if you make a call to a server and want to check a retrieved object against a local object.

const a = {'field': 2} // Non-primitive object
const b = {'field': 2} // Non-primitive object with same value
const c = a            // Non-primitive object that reference the same object as "a"

assert(a !== b) // Don't reference the same item, but have same value
assert(a === c) // Do reference the same item, and have same value (naturally)

//Note: there are many alternative implementations for valuesAreEqual
function valuesAreEqual (x, y) {
   return  JSON.stringify(x) === JSON.stringify(y)
}


//filter will delete false values
//Thus, we want to return "false" if the item
// we want to delete is equal to the item in the array
function removeFromArray(arr, toDelete){
    return arr.filter(target => {return !valuesAreEqual(toDelete, target)})
}

const exampleArray = [a, b, b, c, a, {'field': 2}, {'field': 90}];
const resultArray = removeFromArray(exampleArray, a);

//resultArray = [{'field':90}]

There are alternative/faster implementations for valuesAreEqual, but this does the job. You can also use a custom comparator if you have a specific field to check (for example, some retrieved UUID vs a local UUID).

Also note that this is a functional operation, meaning that it does not mutate the original array.

Aidan Hoolachan

Posted 2011-04-23T22:17:18.487

Reputation: 871

8

In CoffeeScript:

my_array.splice(idx, 1) for ele, idx in my_array when ele is this_value

Nigel Sheridan-Smith

Posted 2011-04-23T22:17:18.487

Reputation: 429

7

Use jQuery's InArray:

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

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

Do Hoa Vinh

Posted 2011-04-23T22:17:18.487

Reputation: 221

5but OP said: "good ol' fashioned JavaScript - no frameworks allowed" – CSᵠ – 2014-12-12T18:51:31.767

for Chrome 50.0, A.splice(-1, 1); will remove the last one in A. – Scott 混合理论 – 2016-06-17T09:38:40.683

6

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

function destroy(arr, val) {
    for (var i = 0; i < arr.length; i++) if (arr[i] === val) arr.splice(i, 1);
    return arr;
}

yckart

Posted 2011-04-23T22:17:18.487

Reputation: 20 370

destroy( [1,2,3,3,3,4,5], 3 ) returns [1,2,3,4,5]]. i should not be incremented when the array is spliced. – Renze de Waal – 2014-01-23T17:34:08.273

@RenzedeWaal this might work if you iterated over i backwards instead of forwards though. for (var i = arr.length; i-- > 0; ) [ edit ] already posted here

– TKoL – 2017-03-03T12:58:00.193

6

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

$(document).ready(function(){
    var arr = ["C#","Ruby","PHP","C","C++"];
    var itemtoRemove = "PHP";
    arr.splice($.inArray(itemtoRemove, arr),1);
});

mboeckle

Posted 2011-04-23T22:17:18.487

Reputation: 585

Removes last item if searched item not found – Hontoni – 2014-04-30T17:05:56.920

1yes correct, you should know which element you want to remove like in the other examples. – mboeckle – 2014-05-01T17:00:06.707

3This is jQuery, not core JavaScript. – Dughall – 2016-04-18T15:31:37.883

any other way for some repeated value max 5 times then create new array and remove that value from array? I HAVE THIS KIND OF ARRAY: ["info.specificAllergy", "info.specificAllergy", "info.specificAllergy", "info.specificAllergy", "info.specificAllergy", "info.existingMedicalCondition", "info.existingMedicalCondition", "info.existingMedicalCondition", "info.existingMedicalCondition", "info.existingMedicalCondition"] – Jignesh Vagh – 2017-07-14T14:22:24.350

6

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

Lars Gyrup Brink Nielsen

Posted 2011-04-23T22:17:18.487

Reputation: 1 949

6

Remove element at index i, without mutating the original array:

/**
* removeElement
* @param {Array} array
* @param {Number} index
*/
function removeElement(array, index) {
   return Array.from(array).splice(index, 1);
}

// Another way is
function removeElement(array, index) {
   return array.slice(0).splice(index, 1);
}

alejandro

Posted 2011-04-23T22:17:18.487

Reputation: 2 153

6

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]

AmerllicA

Posted 2011-04-23T22:17:18.487

Reputation: 3 072

5

By my solution you can remove one or more than one item in an array thanks to pure JavaScript. There is no need for another JavaScript library.

var myArray = [1,2,3,4,5]; // First array

var removeItem = function(array,value) {  // My clear function
    if(Array.isArray(value)) {  // For multi remove
        for(var i = array.length - 1; i >= 0; i--) {
            for(var j = value.length - 1; j >= 0; j--) {
                if(array[i] === value[j]) {
                    array.splice(i, 1);
                };
            }
        }
    }
    else { // For single remove
        for(var i = array.length - 1; i >= 0; i--) {
            if(array[i] === value) {
                array.splice(i, 1);
            }
        }
    }
}

removeItem(myArray,[1,4]); // myArray will be [2,3,5]

Kamuran Sönecek

Posted 2011-04-23T22:17:18.487

Reputation: 1 763

5

I made a fairly efficient extension to the base JavaScript array:

Array.prototype.drop = function(k) {
  var valueIndex = this.indexOf(k);
  while(valueIndex > -1) {
    this.removeAt(valueIndex);
    valueIndex = this.indexOf(k);
  }
};

Shawn Deprey

Posted 2011-04-23T22:17:18.487

Reputation: 506

5

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

Victor

Posted 2011-04-23T22:17:18.487

Reputation: 86

4

Use jQuery.grep():

var y = [1, 2, 3, 9, 4]
var removeItem = 9;

y = jQuery.grep(y, function(value) {
  return value != removeItem;
});
console.log(y)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>

Mahendra Kulkarni

Posted 2011-04-23T22:17:18.487

Reputation: 845

4

While most of the answers above 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 lets 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()

Stelios Voskos

Posted 2011-04-23T22:17:18.487

Reputation: 371

4

Remove one value, using loose comparison, without mutating 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;
}

mpen

Posted 2011-04-23T22:17:18.487

Reputation: 120 158

3

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;

rncrtr

Posted 2011-04-23T22:17:18.487

Reputation: 2 279

3

Remove last occurrence or all occurrences, or first occurrence?

var array = [2, 5, 9, 5];

// Remove last occurrence (or all occurrences)
for (var i = array.length; i--;) {
  if (array[i] === 5) {
     array.splice(i, 1);
     break; // Remove this line to remove all occurrences
  }
}

or

var array = [2, 5, 9, 5];

// Remove first occurrence
for (var i = 0; array.length; i++) {
  if (array[i] === 5) {
     array.splice(i, 1);
     break; // Do not remove this line
  }
}

MEC

Posted 2011-04-23T22:17:18.487

Reputation: 805

3

I made a function

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

And used like this.

pop(valuetoremove,myarray);

Cheers!

Ali Akram

Posted 2011-04-23T22:17:18.487

Reputation: 601

3

Post my code that removes an array element in place, and reduce the array length as well.

function removeElement(idx, arr) {
    // check the index value
    if (idx < 0 || idx >= arr.length) {
        return;
    }
    // shift the elements
    for (var i = idx; i > 0; --i) {
        arr[i] = arr[i - 1];
    }
    // remove the first element in array
    arr.shift();
}

hailong

Posted 2011-04-23T22:17:18.487

Reputation: 427

3

For anyone looking to replicate a method that will return a new array that has duplicate numbers or strings removed, this has been put together from existing answers:

function uniq(array) {
  var len = array.length;
  var dupFree = [];
  var tempObj = {};

  for (var i = 0; i < len; i++) {
    tempObj[array[i]] = 0;
  }

  console.log(tempObj);

  for (var i in tempObj) {
    var element = i;
    if (i.match(/\d/)) {
      element = Number(i);
    }
    dupFree.push(element);
  }

  return dupFree;
}

cjjenkinson

Posted 2011-04-23T22:17:18.487

Reputation: 129

3

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

Gaurang Patel

Posted 2011-04-23T22:17:18.487

Reputation: 139

2

var index,
    input = [1,2,3],
    indexToRemove = 1;
    integers = [];

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

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

penguin

Posted 2011-04-23T22:17:18.487

Reputation: 624

1This is very inefficient when the array is large. – Christophe Roussy – 2014-09-25T14:40:36.063

2

Removing the value with index and splice!

function removeArrValue(arr,value) {
    var index = arr.indexOf(value);
    if (index > -1) {
        arr.splice(index, 1);
    }
    return arr;
}

Nejc Lepen

Posted 2011-04-23T22:17:18.487

Reputation: 137

14Your 2 last comments were just rewriting an accepted answer... Please answer a solved problem only if you have more information to provide than the accepted one. If not, just upvote the accepted answer. – ylerjen – 2014-10-22T14:43:13.110

2

The following method will remove all entries of a given value from an array without creating a new array and with only one iteration which is superfast. And it works in ancient Internet Explorer 5.5 browser:

function removeFromArray(arr, removeValue) {
  for (var i = 0, k = 0, len = arr.length >>> 0; i < len; i++) {
    if (k > 0)
      arr[i - k] = arr[i];

    if (arr[i] === removeValue)
      k++;
  }

  for (; k--;)
    arr.pop();
}

var a = [0, 1, 0, 2, 0, 3];

document.getElementById('code').innerHTML =
  'Initial array [' + a.join(', ') + ']';
//Initial array [0, 1, 0, 2, 0, 3]

removeFromArray(a, 0);

document.getElementById('code').innerHTML +=
  '<br>Resulting array [' + a.join(', ') + ']';
//Resulting array [1, 2, 3]
<code id="code"></code>

Eugene Tiurin

Posted 2011-04-23T22:17:18.487

Reputation: 1 289

2

What a shame you have an array of integers, not an object where the keys are string equivalents of these integers.

I've looked through a lot of these answers and they all seem to use "brute force" as far as I can see. I haven't examined every single one, apologies if this is not so. For a smallish array this is fine, but what if you have 000s of integers in it?

Correct me if I'm wrong, but can't we assume that in a key => value map, of the kind which a JS object is, that the key retrieval mechanism can be assumed to be highly engineered and optimised? (NB if some super-expert tells me that this is not the case, I can suggest using ES6's Map class instead, which certainly will be).

I'm just suggesting that, in certain circumstances, the best solution might be to convert your array to an object... the problem being, of course, that you might have repeating integer values. I suggest putting those in buckets as the "value" part of the key => value entries. (NB if you are sure you don't have any repeating array elements this can be much simpler: values "same as" keys, and just go Object.values(...) to get back your modified array).

So you could do:

const arr = [ 1, 2, 55, 3, 2, 4, 55 ];
const f =   function( acc, val, currIndex ){ 
    // not seen this val before: make bucket... NB although val's typeof is 'number'
    // there is seamless equivalence between the object key (always string)
    // and this variable val 
    ! ( val in acc ) ? acc[ val ] = []: 0;
    // drop another array index in the bucket
    acc[ val ].push( currIndex );
    return acc; 
}
const myIntsMapObj = arr.reduce( f, {});

console.log( myIntsMapObj );

output:

Object [ <1 empty slot>, Array1, Array[2], Array1, Array1, <5 empty slots>, 46 more… ]

it is then easy to delete all the numbers 55

delete myIntsMapObj[ 55 ]; // again, although keys are strings this works

You don't have to delete them all: index values are pushed into their buckets in order of appearance, so (for example):

myIntsMapObj[ 55 ].shift(); // and
myIntsMapObj[ 55 ].pop(); 

will delete the first and last occurrence respectively. You can count frequency of occurrence easily, replace all 55s with 3s by transferring the contents of one bucket to another, etc.

... getting back your modified int array is slightly involved: but each bucket contains the index (in the original array) of the value represented by the (string) key. Each of these bucket values is also unique: so you turn them into keys in a new object, with the (real) integer from the "integer string key" as value... then sort the keys and go Object.values( ... ).

This sounds very involved and time-consuming... but obviously everything depends on the circumstances and desired usage. My understanding is that all versions and contexts of JS operate only in one thread, and the thread doesn't "let go", so there could be some horrible congestion with a "brute force" method: caused not so much by the indexOf ops, but multiple repeated slice/splice ops.

Addendum
If you're sure this is too much engineering for your use case surely the simplest "brute force" approach is

const arr = [ 1, 2, 3, 66, 8, 2, 3, 2 ];
const newArray = arr.filter( number => number !== 3 );
console.log( newArray )

(yes, other answers have spotted Array.prototype.filter...)

mike rodent

Posted 2011-04-23T22:17:18.487

Reputation: 3 625

2

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

sujithklr93

Posted 2011-04-23T22:17:18.487

Reputation: 97

2

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

Srikrushna Pal

Posted 2011-04-23T22:17:18.487

Reputation: 445

2

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

Posted 2011-04-23T22:17:18.487

Reputation: 636

1

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

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

Matt Brock

Posted 2011-04-23T22:17:18.487

Reputation: 4 502

3While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – Krumia – 2015-05-18T03:03:07.167

1Sadly, the internet (and Stack Overflow) are filled with half-implemented, partially-correct versions of ES5 array methods. That is entirely the point of the linking to the polyfill. For a truly complete reproduction of all of the correct behaviors, it isn't good enough to summarize "the essential parts." You have to implement all of the edge conditions as well. To reproduce their content in its entirety is well beyond the scope of Stack Overflow. Stack Overflow is not GitHub. – Matt Brock – 2015-05-18T13:38:48.690

1

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

Steven Spungin

Posted 2011-04-23T22:17:18.487

Reputation: 6 373

1

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.

hygull

Posted 2011-04-23T22:17:18.487

Reputation: 2 846

0

Array.prototype.remove = function(x) {
    var y=this.slice(x+1);
    var z=[];
    for(i=0;i<=x-1;i++) {
        z[z.length] = this[i];
    }

    for(i=0;i<y.length;i++){
        z[z.length]=y[i];
    }

    return z;
}

user4109793

Posted 2011-04-23T22:17:18.487

Reputation:

0

There are already a lot of answers, but because no one has done it with a one liner yet, I figured I'd show my method. It takes advantage of the fact that the string.split() function will remove all of the specified characters when creating an array. Here is an example:

var ary = [1,2,3,4,1234,10,4,5,7,3];
out = ary.join("-").split("-4-").join("-").split("-");
console.log(out);

In this example, all of the 4's are being removed from the array ary. However, it is important to note that any array containing the character "-" will cause issues with this example. In short, it will cause the join("-") function to piece your string together improperly. In such a situation, all of the the "-" strings in the above snipet can be replaced with any string that will not be used in the original array. Here is another example:

var ary = [1,2,3,4,'-',1234,10,'-',4,5,7,3];
out = ary.join("[email protected]#").split("[email protected]#[email protected]#").join("[email protected]#").split("[email protected]#");
console.log(out);

Partial Science

Posted 2011-04-23T22:17:18.487

Reputation: 100

-1

    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]

Zibri

Posted 2011-04-23T22:17:18.487

Reputation: 4 239

-9

var ar1 = [1,2,3,4,5,6,7,8,9]
var toBeRemoved = 2;
ar1.splice( (ar1.length -toBeRemoved) , toBeRemoved);

alowsarwar

Posted 2011-04-23T22:17:18.487

Reputation: 298

-9

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.

Sanya Kravchuk

Posted 2011-04-23T22:17:18.487

Reputation: 9