1133

Is there a method to remove an item from a JavaScript array?

Given an array:

var ary = ['three', 'seven', 'eleven'];

I would like to do something like:

removeItem('seven', ary);

I've looked into splice() but that only removes by the position number, whereas I need something to remove an item by its value.

Paul Roub
  • 35,100
  • 27
  • 72
  • 83
MacMac
  • 30,042
  • 53
  • 142
  • 217
  • 3
    See also: [Remove an array element by value in JavaScript](http://stackoverflow.com/q/7142890/1048572) and [Remove specific element from an array?](http://stackoverflow.com/q/7142890/1048572) – Bergi Aug 11 '14 at 16:47
  • 91
    PLEASE USE --> `Array.filter()` – Eric Hodonsky Mar 20 '17 at 18:08
  • I wrote various solutions for this (remove one or multiple values) and this is my ultimate solution (I benchmarked and it is faster than lodash). Have a go: https://gist.github.com/ardeshireshghi/0d97db4ae09bc2f90609c536fc63c648 – Ardi Oct 04 '17 at 15:03
  • It can also be found here: https://stackoverflow.com/questions/5767325/how-do-i-remove-a-particular-element-from-an-array-in-javascript/21408685#21408685 This is the benchmark: https://jsperf.com/array-without-benchmark-against-lodash – Ardi Oct 04 '17 at 16:36

37 Answers37

1927

You can use the indexOf method like this:

var index = array.indexOf(item);
if (index !== -1) {
  array.splice(index, 1);
}

Note: You'll need to shim it for IE8 and below

var array = [1,2,3,4]
var item = 3

var index = array.indexOf(item);
array.splice(index, 1);

console.log(array)
Maciej Krawczyk
  • 10,012
  • 5
  • 30
  • 38
SLaks
  • 800,742
  • 167
  • 1,811
  • 1,896
  • 72
    And loop on it while the index isn't `-1` – Colin Hebert Oct 17 '10 at 17:50
  • 8
    It would be best to do a check to only splice if different than `-1`, there are like millions of options, choose wisely http://jsperf.com/not-vs-gt-vs-ge/4 – ajax333221 May 29 '12 at 21:19
  • 32
    If you use jquery, you can use `$.inArray` instead of `indexOf`, which is cross browser compatible. – Tamás Pap May 21 '13 at 08:55
  • 4
    Check http://stackoverflow.com/questions/5767325/remove-specific-element-from-an-array – Dimuthu Oct 18 '13 at 05:50
  • 41
    Make sure index!==(-1) , i.e. item exists in array, or else you will splice out the last element in array. – Ronen Rabinovici Oct 27 '13 at 21:08
  • 1
    @unicorn2 - it does not matter. as a developer, you should use a polyfil script to bring older browsers up to standards, so using the best way you can code something is encouraged. – vsync Apr 01 '14 at 14:47
  • var arr = ['aaa', 'bbb', 'ccc']; \n if( !!~arr.indexOf('inputString') ) arr.splice(arr.indexOf('inputString'), 1); – Shawn Wu Sep 29 '16 at 07:26
  • Took me a bit, so here is an example of how to use [$.inArray()](https://api.jquery.com/jQuery.inArray/): `var item_index = $.inArray(value, monsterarray); if(item_index!==-1) { monsterarray.splice(item_index, 1); }` Done. – Avatar Jan 05 '18 at 13:41
  • @FranciscoCouzo Only if you don't use the `fromIndex` parameter. Using it, worst case is still `O(n)`. – Kroltan Feb 16 '18 at 14:54
  • Splice will modify the original array if you only plan to modify only a copy of the array. It took me several hours to discover this splice method caused the unknown error on my code. – JAT86 Sep 06 '20 at 21:41
544

A one-liner will do it,

var ary = ['three', 'seven', 'eleven'];

// Remove item 'seven' from array
var filteredAry = ary.filter(function(e) { return e !== 'seven' })
//=> ["three", "eleven"]

// In ECMA6 (arrow function syntax):
var filteredAry = ary.filter(e => e !== 'seven')

This makes use of the filter function in JS. It's supported in IE9 and up.

What it does (from the doc link)

filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array.

So basically, this is the same as all the other for (var key in ary) { ... } solutions, except that the for in construct is supported as of IE6.

Basically, filter is a convenience method that looks a lot nicer (and is chainable) as opposed to the for in construct (AFAIK).

SidOfc
  • 4,338
  • 3
  • 23
  • 47
John Williams
  • 9,282
  • 4
  • 33
  • 44
  • 7
    Wondering this wonderful one-liner does not get more love. +1 No loops. One can add as many as values he want to remove by using `&&` for values. –  Aug 22 '14 at 16:15
  • @bamboon The filter function checks whether an element meets the criteria. The function is executed with each element one by one and upon returning `true`, the resulting array will retain the element. It is omitted on `false`. – Qwerty Oct 14 '14 at 14:29
  • @vlzvl Probably because some of us still have to [support IE8](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Browser_compatibility), which also rules out using this with Windows Script Host Version 5.8, eg, without a polyfill. Argh. ;^) – ruffin Mar 16 '15 at 17:07
  • 1
    This is really straightforward, with the caveat mentioned by @SLaks that it creates a copy of the array, and doesn't affect references to the variable. – tobylaroni May 19 '15 at 12:57
  • Note that this solution removes ALL elements in the array with a value "seven", not just the first like the highest voted answer does – Zach Saucier Nov 23 '15 at 22:02
  • 12
    Note that this should be used as `array = array.filter()`, not just `array.filter()`. – Jeffrey Roosendaal Nov 30 '15 at 14:19
  • 8
    Updated answer with @JeffreyRoosendaal contribution (`filter() does not mutate the array on which it is called.` from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter ). – Manolo Jan 14 '16 at 15:02
  • This solution can also be used to find a value in an aray of objects e.g. `routes = routes.filter(function (e) { return e.id !== id });` – quilkin Oct 30 '20 at 14:42
539

This can be a global function or a method of a custom object, if you aren't allowed to add to native prototypes. It removes all of the items from the array that match any of the arguments.

Array.prototype.remove = function() {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};

var ary = ['three', 'seven', 'eleven'];

ary.remove('seven');

/*  returned value: (Array)
three,eleven
*/

To make it a global-

function removeA(arr) {
    var what, a = arguments, L = a.length, ax;
    while (L > 1 && arr.length) {
        what = a[--L];
        while ((ax= arr.indexOf(what)) !== -1) {
            arr.splice(ax, 1);
        }
    }
    return arr;
}
var ary = ['three', 'seven', 'eleven'];
removeA(ary, 'seven');


/*  returned value: (Array)
three,eleven
*/

And to take care of IE8 and below-

if(!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(what, i) {
        i = i || 0;
        var L = this.length;
        while (i < L) {
            if(this[i] === what) return i;
            ++i;
        }
        return -1;
    };
}
Community
  • 1
  • 1
kennebec
  • 94,076
  • 30
  • 99
  • 125
  • Just wondering, would I need to include the prototypeJS lib into my project to use your suggestion or is this cross-browser included? – xorinzor Jul 22 '12 at 13:47
  • 5
    @xorinzor No, the .prototype property is cross-browser. – Casey Rodarmor Oct 05 '12 at 05:08
  • 178
    Never change Array prototype. Funny things starts to happen. – szanata May 07 '13 at 12:46
  • 26
    @madeinstefano, one or two examples of the funny (bad) things that would happen? – Majid Fouladpour Jul 23 '13 at 22:38
  • 1
    This is a good solution. Thanks. Just note that – unicorn2 Oct 17 '13 at 09:45
  • 1
    @Doorknob this solution has quadratic asymptotic complexity in speed, while the algorithm is really linear. –  Oct 31 '13 at 07:34
  • very bad solution in while it running indexOf on each iteration, take a look at http://stackoverflow.com/questions/7310559/the-best-way-to-remove-array-element-by-value/7310618#7310618 – IvanM Apr 18 '14 at 08:57
  • @user797257, for(var key in arr) { %use key in some way% } in IE8 will also give you 'indexOf' as one of elements of the array. – boades Nov 24 '14 at 13:36
  • 24
    why do people show examples adding to the array prototype? stack overflow is for learning good practices – Blair Anderson Dec 06 '14 at 00:49
  • 2
    @YoYoYonnY You are missing all JS frameworks.... They ALL use `for(var key in arr){ }` at some point. I'm talking about jQuery, AngularJS... Some of the biggest. – Yonn Trimoreau Jun 29 '15 at 12:52
  • 9
    @YonnTrimoreau and what? define a non-enumerable property `Object.defineProperty(Array.prototype, "remove", {enumerable : false});` – naXa Aug 28 '15 at 09:38
  • 4
    Directly hacking the prototypes of native objects is rarely a clever idea in JavaScript. You may create unpredictable problems. If another framework tries to iterate over the array by keys, your function will be one of the values output. This is not cool in the case of an array. If you wish to modify the Array prototype, follow @naXa 's advice and use Object.defineProperty. Note that this will sacrifice <=IE8 support. There is no way to polyfill Object.defineProperty because it's a low level language feature. – superluminary May 12 '16 at 12:59
  • 1
    @YoYoYonnY Imagine JS world where everyone thinks to change prototype is OK for some random functions. if you change prototype, other libraries change it and all other dependencies change (it's normal these days to have tens of dependencies, so chance of 2 libs that changed function increases), then you finally will mess something and you, or your unlucky colleagues will have the worst days ever finding what's wrong. While your comment is 2 years old, i hope you already learned a lot more about prototype and how tricky it can become and how it's used and when it's ok to change. – Lukas Liesis Feb 09 '17 at 14:45
  • 1
    @LukasLiesis So you are clearly not understanding my comment. My whole point is that you can do whatever you want with prototypes, macros, and recursion as long as you don't have to interact with other code, or you know those interactions are safe. Your point that dependencies might change and break existing code using `prototype` adds nothing to this. I did, and do, in fact, know what there is to know about prototypes as well as preprocessors, recursion, LinkedLists, etc. and it annoys me a lot that there are people claiming you should never use them simply because you could use them wrongly. – yyny Feb 10 '17 at 13:32
  • 2
    @LukasLiesis Furthermore, I have legitimately found people who refuse to use `prototype`, preprocessors, LinkedLists, whatever, simply because someone on the internet, usually StackOverflow, told them that they should never use them. This is just not true. There is "good practice", and there is false information, and the statement like "`prototype` should never be used on existing objects" is simply not good practice. MDN happily defines polyfills for several functions in `Array.prototype`. Some of these will break badly written existing code. But MDN is not at fault, the bad programmers are. – yyny Feb 10 '17 at 13:44
  • @LukasLeisis Lastly, to add to the previous discussion about `for in` loops; The _real_ 'good practice' here is to never use them without a `Object.hasOwnProperty` check. In the case of Array, you would want to use `for (var i=0, len=a.length; i < len; i++) { let v = a[i]; /* ... */ }` instead. Or, if you really want to use `for in`, make sure your code is safe before you do, for example by removing all properties in `Array.prototype` found with a `for in` loop over an empty array, and re-defining them with `Object.defineProperty(Array.prototype, key, {enumerable: false});` as @naXa suggested. – yyny Feb 10 '17 at 13:50
  • @YoYoYonnY I'm not saying that you should never ever extend prototype. Just I think extending it for some random utility functions is not a good idea. – Lukas Liesis Feb 11 '17 at 16:32
  • This is a SUPER bad idea; when you spend 5 hours debugging an issue that is caused by this you'll realize this. – jadkik94 Mar 30 '17 at 19:34
  • 1
    do this: ` var arr = [5, 15, 110, 210, 550]; var index = arr.indexOf(210); if (index > -1) { arr.splice(index, 1); }` – virtualLast Aug 15 '17 at 08:43
142

You can use underscore.js. It really makes things simple.

For example, with this:

var result = _.without(['three','seven','eleven'], 'seven');

And result will be ['three','eleven'].

In your case the code that you will have to write is:

ary = _.without(ary, 'seven')

It reduces the code that you write.

Julius Musseau
  • 3,681
  • 20
  • 25
vatsal
  • 3,387
  • 1
  • 17
  • 19
  • 16
    I never said don't use the library in other places. If the code looks cleaner then i don't mind including a library. Why do people use jquery , why not use raw javascript then? – vatsal Mar 04 '13 at 05:17
  • 11
    @vatsal - because library developers can concentrate on making the functions behind their library functions fast, concise and cross browser, while I get to concentrate on my application and its purpose. It saves me thinking time so that I have extra time to make the application better and not worrying about the small functions that makeup my application. Someone already invented the wheel, why would someone remake it every time they build a car? – styks May 13 '14 at 13:05
  • 11
    Hi Kelvin i totally agree with you. A person had a put a comment and he removed it later, he was saying that using libraries like underscore is not cool and we should not accept such answers. I was trying to answer it. – vatsal May 13 '14 at 13:37
  • Do note this will not modify the array in place; A new array will be returned instead. – gcscaglia Feb 22 '17 at 20:42
63

You can do it with these two ways:

const arr = ['1', '2', '3', '4'] // we wanna delete number "3"
  1. The first way:

    arr.indexOf('3') !== -1 && arr.splice(arr.indexOf('3'), 1)
    
  2. The second way (ES6) specially without mutate:

    const newArr = arr.filter(e => e !== '3')
    
AmerllicA
  • 15,720
  • 11
  • 72
  • 103
54

Check out this way:

for(var i in array){
    if(array[i]=='seven'){
        array.splice(i,1);
        break;
    }
}

and in a function:

function removeItem(array, item){
    for(var i in array){
        if(array[i]==item){
            array.splice(i,1);
            break;
        }
    }
}

removeItem(array, 'seven');
gadlol
  • 1,183
  • 2
  • 12
  • 23
  • 19
    Keep in mind if you modify this code to not "break" and continue looping to remove multiple items, you'll need to recalculate the i variable right after the splice, like so: i--. That's because you just shrunk the array and you'll end up skipping an element otherwise. – Doug S Oct 27 '12 at 05:44
  • 4
    To add to my above comment, the code would then be: for (var i = 0; i < array.length; i++) {/*etc...*/ array.splice(i,1); i--; – Doug S Oct 27 '12 at 05:49
  • Hi... Question, how to remove multiple array? I tried `removeItem(array, 'seven, eight')` but it's not working. – HiDayurie Dave Jan 01 '21 at 04:27
40

The simplest solution is:

array - array for remove some element valueForRemove; valueForRemove - element for remove;

array.filter(arrayItem => !array.includes(valueForRemove));

More simple:

array.filter(arrayItem => arrayItem !== valueForRemove);

No pretty, but works:

array.filter(arrayItem => array.indexOf(arrayItem) != array.indexOf(valueForRemove))

No pretty, but works:

while(array.indexOf(valueForRemove) !== -1) {
  array.splice(array.indexOf(valueForRemove), 1)
}

P.S. The filter() method creates a new array with all elements that pass the test implemented by the provided function. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Jackkobec
  • 3,665
  • 23
  • 22
  • Thats not even close to the correct answer? You should edit this for the working example. It's confusing now. – Arnas Pecelis Mar 04 '19 at 15:02
  • 2
    while i like this approach because it uses immutable data structures, this isn't a catch-all solution because sometimes the developer _does_ want to mutate the array in place – feihcsim Aug 15 '19 at 15:43
  • The filter() method creates a new array with all elements that pass the test implemented by the provided function. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter – Jackkobec Aug 15 '19 at 16:11
  • 1
    This works as the right side of an assignment: `newArray = array.filter...` Then: `array = newArray` and the item is gone from `array`. – Preston Jan 17 '20 at 17:36
  • Documentation about filter() is absolutely understandable. – Jackkobec Jan 17 '20 at 21:11
36

Here's a version that uses jQuery's inArray function:

var index = $.inArray(item, array);
if (index != -1) {
    array.splice(index, 1);
}
CorayThan
  • 15,119
  • 26
  • 101
  • 148
  • 18
    Splice supports negative indices to take from the end, so if the item is not found, this code removes the last item from the array. – dmeglio Apr 21 '15 at 13:04
  • 2
    @dman2306 Huh, didn't see your comment until now, but that's a really good point. Fixed it for that issue. – CorayThan Mar 23 '17 at 19:46
34

Simply

var ary = ['three', 'seven', 'eleven'];
var index = ary.indexOf('seven'); // get index if value found otherwise -1

if (index > -1) { //if found
  ary.splice(index, 1);
}
Olcay Ertaş
  • 5,374
  • 8
  • 71
  • 98
Matee Gojra
  • 3,005
  • 2
  • 23
  • 30
  • 3
    Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation would greatly improve its long-term value](//meta.stackexchange.com/q/114762/206345) by showing _why_ this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you've made. – Goodbye StackExchange Oct 29 '18 at 18:02
  • 2
    worked best in my case as I wanted to delete from an array with the value (to delete) stored to a variable. Thanks! – Akhil May 19 '20 at 14:56
31
var index = array.indexOf('item');

if(index!=-1){

   array.splice(index, 1);
}
Kld
  • 6,430
  • 3
  • 33
  • 49
27

You can create your own method, passing throught the array and the value you want removed:

function removeItem(arr, item){
 return arr.filter(f => f !== item)
}

Then you can call this with:

ary = removeItem(ary, 'seven');
Chiaro
  • 1,134
  • 10
  • 11
18

What you're after is filter

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

This will allow you to do the following:

var ary = ['three', 'seven', 'eleven'];
var aryWithoutSeven = ary.filter(function(value) { return value != 'seven' });
console.log(aryWithoutSeven); // returns ['three', 'eleven']

This was also noted in this thread somewhere else: https://stackoverflow.com/a/20827100/293492

Community
  • 1
  • 1
Lotus
  • 2,376
  • 1
  • 20
  • 18
16

ES6 way.

const commentsWithoutDeletedArray = commentsArray.filter(comment => comment.Id !== commentId);
Oliver Dixon
  • 6,069
  • 5
  • 52
  • 82
  • I think mapreduce functions in javascript are pretty fast, but splice would still be faster. so a better implementation might be `const removeArrayItem = (arr, itemToRemove) => { return arr.includes(itemToRemove)? arr.splice(arr.indexOf(itemToRemove), 1): arr }` – roberto tomás Jul 26 '17 at 14:51
  • 7
    @robertotomás I prefer readability over slight performance gains. – Oliver Dixon Dec 01 '18 at 13:38
  • Hey @OliverDixon can u please explain more `comment.Id !== commentId` now the commecnt i want delete is 5 now in filter `5 !== 5` it's false so how dose delete it :\? – Oliver D Sep 28 '20 at 13:49
  • @OliverDixon in case you need the performance, you can simply wrap that unreadable code into your own readable function. – rpgs_player Nov 19 '20 at 08:48
14

Seeing as there isn't a pretty one, here's a simple and reusable ES6 function.

const removeArrayItem = (arr, itemToRemove) => {
  return arr.filter(item => item !== itemToRemove)
}

Usage:

const items = ['orange', 'purple', 'orange', 'brown', 'red', 'orange']
removeArrayItem(items, 'orange')
Shakespeare
  • 1,296
  • 8
  • 15
  • 4
    removeArrayItem method doesn't remove item from the array. It creates new array without item. – WebBrother Nov 27 '17 at 16:06
  • Correct @WebBrother. From a 'consumer' point of view, the implementation is not really my concern - if I give it an array and an item, I get an array back with the item removed, so the name makes sense to me. Thoughts? – Shakespeare Dec 08 '17 at 11:09
  • If you're going to use ES6, make sure you're using the correct comparison (avoid !== and instead use !Object.is(item, itemToRemove). – Sterling Bourne Jun 05 '18 at 20:13
12

When you need to remove a value present multiple times in the array(e.g. [1,2,2,2, 4, 5,6]).

function removeFrmArr(array, element) {
  return array.filter(e => e !== element);
};
var exampleArray = [1,2,3,4,5];
removeFrmArr(exampleArray, 3);
// return value like this
//[1, 2, 4, 5]

You can use splice to remove a single element from the array but splice can't remove multiple similar elements from the array.

function singleArrayRemove(array, value){
  var index = array.indexOf(value);
  if (index > -1) array.splice(index, 1);
  return array;
}
var exampleArray = [1,2,3,4,5,5];
singleArrayRemove(exampleArray, 5);
// return value like this
//[1, 2, 3, 4, 5]
Olcay Ertaş
  • 5,374
  • 8
  • 71
  • 98
Subhojit Mondal
  • 405
  • 6
  • 15
12

Really, i can't see why this can't be solved with

arr = arr.filter(value => value !== 'seven');

Or maybe you want to use vanilla JS

arr = arr.filter(function(value) { return value !== 'seven' });
rbenvenuto
  • 2,345
  • 2
  • 10
  • 19
11

If you have unique values in your array and ordering doesn't matter, you can use Set, and it has delete:

var mySet = new Set(['foo']);
mySet.delete('foo'); // Returns true.  Successfully removed.
mySet.has('foo');    // Returns false. The "foo" element is no longer present.
Dan H
  • 11,508
  • 5
  • 35
  • 32
greene
  • 440
  • 3
  • 5
8

In all values unique, you can:

a = new Set([1,2,3,4,5]) // a = Set(5) {1, 2, 3, 4, 5}
a.delete(3) // a = Set(5) {1, 2, 4, 5} 
[...a] // [1, 2, 4, 5]
Eugene Lyzo
  • 101
  • 1
  • 2
7

Removing all matching elements from the array (rather than just the first as seems to be the most common answer here):

while ($.inArray(item, array) > -1) {
    array.splice( $.inArray(item, array), 1 );
}

I used jQuery for the heavy lifting, but you get the idea if you want to go native.

Jason
  • 2,059
  • 2
  • 21
  • 22
  • 4
    So you run $.inArray twice if an item is found, why not store the index on the first run and re-use that? #effectiveprogramming #resourcesdonotgrowontrees. while( ( index = $.inArray(item,array) ) > -1 ) array.splice( index, 1 ); – patrick May 29 '17 at 13:56
6

a very clean solution working in all browsers and without any framework is to asign a new Array and simply return it without the item you want to delete:

/**
 * @param {Array} array the original array with all items
 * @param {any} item the time you want to remove
 * @returns {Array} a new Array without the item
 */
var removeItemFromArray = function(array, item){
  /* assign a empty array */
  var tmp = [];
  /* loop over all array items */
  for(var index in array){
    if(array[index] !== item){
      /* push to temporary array if not like item */
      tmp.push(array[index]);
    }
  }
  /* return the temporary array */
  return tmp;
}
dcordz
  • 103
  • 1
  • 7
mtizziani
  • 808
  • 9
  • 20
  • +1 for a clean solution. Too many answers tend to suggest one 3rd party resource or another when sometimes we need a purer solution (and they are all great just not in all use cases). – Trevor Jun 29 '16 at 15:54
5

You can achieve this using Lodash _.remove function.

var array = ['three', 'seven', 'eleven'];
var evens = _.remove(array, function(e) {
  return e !== 'seven';
});

console.log(evens);
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
Penny Liu
  • 7,720
  • 5
  • 40
  • 66
4

indexOf is an option, but it's implementation is basically searching the entire array for the value, so execution time grows with array size. (so it is in every browser I guess, I only checked Firefox).

I haven't got an IE6 around to check, but I'd call it a safe bet that you can check at least a million array items per second this way on almost any client machine. If [array size]*[searches per second] may grow bigger than a million you should consider a different implementation.

Basically you can use an object to make an index for your array, like so:

var index={'three':0, 'seven':1, 'eleven':2};

Any sane JavaScript environment will create a searchable index for such objects so that you can quickly translate a key into a value, no matter how many properties the object has.

This is just the basic method, depending on your need you may combine several objects and/or arrays to make the same data quickly searchable for different properties. If you specify your exact needs I can suggest a more specific data structure.

aaaaaaaaaaaa
  • 3,434
  • 1
  • 21
  • 23
  • Mind that this is NOT clugy as an associative array is actually an object: var arr = []; arr['zero'] = 1, arr['one'] = 2; is equivalent to: {zero: 1, one: 2} – Cody Sep 11 '12 at 20:11
3

The trick is to go through the array from end to beginning, so you don't mess up the indices while removing elements.

var deleteMe = function( arr, me ){
   var i = arr.length;
   while( i-- ) if(arr[i] === me ) arr.splice(i,1);
}

var arr = ["orange","red","black", "orange", "white" , "orange" ];

deleteMe( arr , "orange");

arr is now ["red", "black", "white"]

2

You can use without or pull from Lodash:

const _ = require('lodash');
_.without([1, 2, 3, 2], 2); // -> [1, 3]
sakovias
  • 1,216
  • 1
  • 17
  • 22
2

Non-destructive removal:

function removeArrayValue(array, value)
{
    var thisArray = array.slice(0); // copy the array so method is non-destructive

    var idx = thisArray.indexOf(value); // initialise idx

    while(idx != -1)
    {
        thisArray.splice(idx, 1); // chop out element at idx

        idx = thisArray.indexOf(value); // look for next ocurrence of 'value'
    }

    return thisArray;
}
Randhir Rawatlal
  • 185
  • 1
  • 1
  • 12
1
var remove = function(array, value) {
    var index = null;

    while ((index = array.indexOf(value)) !== -1)
        array.splice(index, 1);

    return array;
};
Alexander Abashkin
  • 1,039
  • 4
  • 12
  • 18
1

Please do not use the variant with delete - it makes a hole in the array as it does not re-index the elements after the deleted item.

> Array.prototype.remove=function(v){
...     delete this[this.indexOf(v)]
... };
[Function]
> var myarray=["3","24","55","2"];
undefined
> myarray.remove("55");
undefined
> myarray
[ '3', '24', , '2' ]
mmohab
  • 2,073
  • 4
  • 23
  • 40
Ilya Sher
  • 551
  • 4
  • 4
1

I used the most voted option and created a function that would clean one array of words using another array of unwanted words:

function cleanArrayOfSpecificTerms(array,unwantedTermsArray) {
  $.each(unwantedTermsArray, function( index, value ) {
    var index = array.indexOf(value);
    if (index > -1) {
      array.splice(index, 1);        
    }
  });
  return array;
}

To use, do the following:

var notInclude = ['Not','No','First','Last','Prior','Next', 'dogs','cats'];
var splitTerms = ["call", "log", "dogs", "cats", "topic", "change", "pricing"];

cleanArrayOfSpecificTerms(splitTerms,notInclude)
maudulus
  • 9,035
  • 7
  • 64
  • 101
1
let arr = [5, 15, 25, 30, 35];
console.log(arr); //result [5, 15, 25, 30, 35]
let index = arr.indexOf(30);

if (index > -1) {
   arr.splice(index, 1);
}
console.log(arr); //result [5, 15, 25, 35]
Asif vora
  • 1,117
  • 2
  • 8
  • 19
1

In a global function we can't pass a custom value directly but there are many way as below

 var ary = ['three', 'seven', 'eleven'];
 var index = ary.indexOf(item);//item: the value which you want to remove

 //Method 1
 ary.splice(index,1);

 //Method 2
 delete ary[index]; //in this method the deleted element will be undefined
Srikrushna
  • 2,652
  • 30
  • 37
1

Check out this way:

delete this.arrayName[this.arrayName.indexOf(value)];

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

JK_
  • 51
  • 2
  • Using delete on an item in an array leaves an "empty slot" in the array (leaving array.length unchanged). Probably not what the OP or anyone reading this answer is looking for. – keymap Feb 25 '21 at 04:50
0

I tried using the function method from jbaron above but found that I needed to keep the original array intact for use later, and creating a new array like this:

var newArray = referenceArray;

apparently creates by reference instead of value because when I removed an element from newArray the referenceArray also had it removed. So I decided to create a new array each time like this:

function newArrRemoveItem(array, item, newArray){
    for(var i = 0; i < array.length; i++) {
        if(array[i]!=item){
            newArray.push(array[i]);
        }
    }
}

Then I use it like this in another function:

var vesselID = record.get('VesselID');
var otherVessels = new Array();
newArrRemoveItem(vesselArr,vesselID,otherVessels);

Now the vesselArr remains intact while each time I execute the above code the otherVessels array includes all but the latest vesselID element.

Robert
  • 117
  • 2
  • 15
0
//This function allows remove even array from array
var removeFromArr = function(arr, elem) { 
    var i, len = arr.length, new_arr = [],
    sort_fn = function (a, b) { return a - b; };
    for (i = 0; i < len; i += 1) {
        if (typeof elem === 'object' && typeof arr[i] === 'object') {
            if (arr[i].toString() === elem.toString()) {
                continue;
            } else {                    
                if (arr[i].sort(sort_fn).toString() === elem.sort(sort_fn).toString()) {
                    continue;
                }
            }
        }
        if (arr[i] !== elem) {
            new_arr.push(arr[i]);
        }
    }
    return new_arr;
}

Example of using

var arr = [1, '2', [1 , 1] , 'abc', 1, '1', 1];
removeFromArr(arr, 1);
//["2", [1, 1], "abc", "1"]

var arr = [[1, 2] , 2, 'a', [2, 1], [1, 1, 2]];
removeFromArr(arr, [1,2]);
//[2, "a", [1, 1, 2]]
yesnik
  • 2,425
  • 23
  • 20
0

Another variation:

if (!Array.prototype.removeArr) {
    Array.prototype.removeArr = function(arr) {
        if(!Array.isArray(arr)) arr=[arr];//let's be nice to people who put a non-array value here.. that could be me!
        var that = this;
        if(arr.length){
            var i=0;
            while(i<that.length){
                if(arr.indexOf(that[i])>-1){
                    that.splice(i,1);
                }else i++;
            }
        }
        return that;
    }
}

It's indexOf() inside a loop again, but on the assumption that the array to remove is small relative to the array to be cleaned; every removal shortens the while loop.

dkloke
  • 336
  • 3
  • 11
-1

CoffeeScript+jQuery variant:

arrayRemoveItemByValue = (arr,value) ->
  r=$.inArray(value, arr)
  unless r==-1
    arr.splice(r,1)
  # return
  arr

console.log arrayRemoveItemByValue(['2','1','3'],'3')

it remove only one, not all.

Igor Teterin
  • 113
  • 6
-1

//edited thanks to MarcoCI for the advice

try this:

function wantDelete(item, arr){
  for (var i=0;i<arr.length;i++){
    if (arr[i]==item){
      arr.splice(i,1); //this delete from the "i" index in the array to the "1" length
      break;
    }
  }  
}
var goodGuys=wantDelete('bush', ['obama', 'bush', 'clinton']); //['obama', 'clinton']

hope this help you

Sevle
  • 3,014
  • 2
  • 17
  • 28
julian
  • 125
  • 1
  • 7
  • 5
    An explanation, even if brief, is better than just dumping a chunk of code. – j08691 Mar 20 '15 at 21:18
  • Do not use `for in` for arrays, it's bad practice and if somebody touches the Array prototype you're done. – MarcoL Mar 20 '15 at 22:51
-1

You can use lodash pull function

var ary = ['three', 'seven', 'eleven'];
_.pull(ary, 'seven'); // ['three', 'eleven']
console.log(ary)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.6.1/lodash.js"></script>
Parth Raval
  • 3,325
  • 2
  • 20
  • 30