How can I remove a specific item from an array in JavaScript?
Asked Answered
R

154

11899

How do I remove a specific value from an array? Something like:

array.remove(value);

Constraints: I have to use core JavaScript. Frameworks are not allowed.

Redan answered 23/4, 2011 at 22:17 Comment(6)
array.remove(index) or array.pull(index) would make a lot of sense. splice is very useful, but a remove() or pull() method would be welcome... Search the internet, you will find a lot of "What is the opposite of push() in JavaScript?" questions. Would be great if the answare could be as simples as plain english: Pull!Barmy
Anyone checking this question, do see the problems associated with using delete for arrays mentioned by SasaPhillisphilly
@Gustavo Gonçalves I do not understand the problem: the opposite of Array#push() is well-known. (Of course, that is not what this question is asking for.)Unscrupulous
In modern JavaScript (ES6) you can use Sets which have a in-built Set.delete(elmnt) methodRhoda
@GustavoGonçalves yes. arrays should have a remove method and if anyone says "what about if the developer added it already?" then make it a weak add. If the remove member/function does not exist on the array then add it. Array needs it.Rudolf
@1.21gigawatts that doesn't work because the custom remove method can have different signature or semantics from one added later. Therefore arr.remove(foo) can start to behave differently if it's later added to arrays and your custom method addition yields to that implementation. And that's not even a hypothetical, it's something that happens with MooTools and Array#contains. This literally had an effect of the whole of the internet because contains was removed to includes to avoid that clash.Hughmanick
B
16629

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

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

const array = [2, 5, 9];

console.log(array);

const index = array.indexOf(5);
if (index > -1) { // only splice array when item is found
  array.splice(index, 1); // 2nd parameter means remove one item only
}

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


For the reason of completeness, here are functions. The first function removes only a single occurrence (i.e. removing the first match of 5 from [2,5,9,1,5,8,5]), while the second function removes all occurrences:

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

function removeItemAll(arr, value) {
  var i = 0;
  while (i < arr.length) {
    if (arr[i] === value) {
      arr.splice(i, 1);
    } else {
      ++i;
    }
  }
  return arr;
}
// Usage
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
console.log(removeItemAll([2,5,9,1,5,8,5], 5))

In TypeScript, these functions can stay type-safe with a type parameter:

function removeItem<T>(arr: Array<T>, value: T): Array<T> { 
  const index = arr.indexOf(value);
  if (index > -1) {
    arr.splice(index, 1);
  }
  return arr;
}
Bursa answered 23/4, 2011 at 22:17 Comment(24)
Serious question: why doesn't JavaScript allow the simple and intuitive method of removing an element at an index? A simple, elegant, myArray.remove(index); seems to be the best solution and is implemented in many other languages (a lot of them older than JavaScript.)Megawatt
@Megawatt developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Bridegroom
@Bridegroom sets and arrays are two completely different collection types.Quill
You can simplify this solution by counting down instead of up: for ( var i = ary.length - 1; i >= 0; i-- ) { if ( ary[i] === value ) { ary.remove(i)} }Microgram
function remove(item,array) { var new_array = [] new_ array = array.filter((ar)=> ar != item) return new_array }Sapsago
Return statement is misleading. Array is already modified. It can confuse that origin array will be untouched.Critchfield
Array.pull() is what humankind needs the most.Dysteleology
I'm a bit late to the party, but here's my two cents: @a2br: Array.unshift() is basically what pull() would be if it existed! @Bob: Personally, I think it's good that nothing similar to Array.remove() exists. We don't want JavaScript to end up like PHP, now do we? xDJoiner
@OOPSStudio actually such method might also reset indexes of remaining elements in the array (making --index for each remaining one), not just removing the element in question and its index too. For such reason, the original array might stay the same and the method might return a new array (similar to what makes the filter() method). Extreme scenarios are when no element gets removed (so no new array is created) or when all elements are removed (so we get a zero-length new generated array). The method might then cover as many use scenarios as possible not just removing an elementNaevus
Great answer. The condition if (index > -1) is very important because if the element is not found arr.indexOf(value) returns -1. array.splice(-1) will delete the last element of the array instead of preventing any deletionRaymonraymond
I think the best solution would be using .filter, I'm afraid that many beginners would think the above solution is the advised one when it's not. Iterating over an array and using splice several times would be considered legacy nowadays. This answer has a score of 15K, I think it can be improvedSmelser
If only json supported sets, then we could use sets instead :(Pallette
How to remove value from array with the value, not the index?Deutzia
@CodemasterUnited array.splice(array.indexOf("value"), 1)Harborage
I used the code above, but why [1].splice(0, 1); gives [1]? Should the splice not return an empty array []. .... Ah, found the answer here: https://mcmap.net/q/32995/-why-doesn-39-t-array-splice-work-when-the-array-has-only-1-element/1066234 "it returns what was removed, but the array is empty"Prothrombin
Use the .findIndex(o => o.property === valueToCompare) method to get an index of an object from the array.Enidenigma
hi i have array '{62 => 105, 59 => 3.33}' i wnat to delete 59 and its value how i can do thatMerciless
@jave.web if then why not do this arr[index] = undefined ? @OOPSStudio why not you want to take something from PHP that is better than JS? @Naevus that kind of method should be used when existing indexes aren't important. Btw, I've just expressed my thoughts & I fully respectful to all of your thoughts.Profusive
hacky (has unexpected length behavior): to keep the indexes untouched and just remove the value, you can do delete arr[index] - be aware that the .length will still remain the same (so push will still increase the index), but Array.forEach will skip this index and if you will try to access the index, you will get undefined @Md.A.Apu I was wrong, Array.forEach SKIPS the index after all... so it's not equivalent of = undefinedEddyede
@Eddyede the length behaviour is not unexpected at all, but that's because of what array length means in JS. Since arrays are just objects (like everything else) that allow numbers as property name (rather than strings), the length value cannot tell you how many elements are in an array. It can only track the highest index used. Which is why a=[]; a[499] = 1; has length 500 even though it only contains one thing, and iterating over that array will only yield that one thing, which is why delete works so well. The real problem is think you can rely on the length property for loops =DPamilapammi
@Mike'Pomax'Kamermans thanks for nice example - however it doesn't change the fact that most people do not expect this - therefore - unexpected (for most). If anyone works with unique values anyways, new Set may be the way.Eddyede
Aye, but that's one of those "if this is unexpected to you, let's learn about what JS calls "arrays" and how they're not" (which is always a great lesson). As for sets, they're insertion-ordered, and don't allow repetition, so they're definitely useful but there's far too many cases where it can't substitute for an array.Pamilapammi
@Mike 'Pomax' Kamermans to be fair, Javascript defines array by the methods, not by their implementation. so "learn what JS calls 'arrays'" depends on the engine being used. you can see this in the NOTE after each function in the specs (262.ecma-international.org/5.1/#sec-15.4) where it says the function is generic.Ghent
arrays should have a remove method and if anyone says "what about if the developer added it already?" then make it a weak add. If the remove member/function does not exist on the array then add itRudolf
G
2503

Edited on 2016 October

  • Do it simple, intuitive and explicit (Occam's razor)
  • Do it immutable (original array stays unchanged)
  • Do it with standard JavaScript functions, if your browser doesn't support them - use polyfill

In this code example I use array.filter(...) function to remove unwanted items from an array. This function doesn't change the original array and creates a new one. If your browser doesn't support this function (e.g. Internet Explorer before version 9, or Firefox before version 1.5), consider polyfilling with core-js.

Be mindful though, creating a new array every time takes a big performance hit. If the list is very large (think 10k+ items) then consider using other methods.

Removing item (ECMA-262 Edition 5 code AKA old style JavaScript)

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 (ECMAScript 6 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 ECMAScript 6 () => {} arrow function syntax is not supported in Internet Explorer at all, Chrome before version 45, Firefox before version 22, and Safari before version 10. To use ECMAScript 6 syntax in old browsers you can use BabelJS.


Removing multiple items (ECMAScript 7 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 Internet Explorer at all, Chrome before version 47, Firefox before version 43, Safari before version 9, and Edge before version 14 but you can polyfill with core-js.

Removing multiple items (in the future, maybe)

If the "This-Binding Syntax" proposal is ever accepted, you'll be able to do this:

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

Glowing answered 19/12, 2013 at 19:54 Comment(5)
what if content of array are objects and nested objectsPanjandrum
doesn't filter return an empty array if the condition isn't met? So you have to be sure the element is going to be there or you're getting it empty on return.Eamon
The above answer would work only for primitive data types though for JavaScript as the object equality is not strictHibernal
Doesn't work if I want to remove only one 3 from the arrayRaymonraymond
arrays should have a remove method and if anyone says "what about if the developer added it already?" then make it a weak add. If the remove member/function does not exist on the array then add itRudolf
E
1772

I don't know how you are expecting array.remove(int) to behave. There are three possibilities I can think of that you might want.

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];
Evince answered 23/4, 2011 at 22:20 Comment(4)
delete array[i] would degrade the performance of the application and is considered a bad praticeSmelser
To those arriving here from search: be sure to understand the code. For instance, note how the array is traversed in reverse; this is the only way splice can be used safely in a loop.Logographic
To add to what Christian said - you can look into how Chrome's V8 engine handles delete. When it encounters delete, it has to drop a lot of optimizations.Importunate
what if you did delete array[array.indexOf(value)]; and the array returns -1? will it work?Rudolf
A
677

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

If you do want an empty slot:

array[index] = undefined;

If you don't want an empty slot:

//To keep the original:
//oldArray = [...array];

//This modifies the array.
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];

If you want to remove at either end of the array, you can use array.pop() for the last one or array.shift() for the first one (both return the value of the item as well).

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. 

Amice answered 23/4, 2011 at 22:32 Comment(2)
It's kinda funny that splice returns another array built out of the removed elements. I wrote something which assumed splice would return the newly modified list (like what immutable collections would do, for example). So, in this particular case of only one item in the list, and that item being removed, the returned list is exactly identical to the original one after splicing that one item. So, my app went into an infinite loop.Advertence
Note that, due to how arrays work, deleting doesn't actually "leave an empty slot" at all. Arrays in JS don't have slots, they're JS objects that are allowed to use numbers as property names, so using delete simply deletes the key/value pair from the object in exactly the same way that delete obj.foo works. You might think that there is an empty slot because accessing array[4] yields undefined after you delete it, but that's just what JS does for non-existent property names. It's not the value that's undefined, the entire property no longer exists because you deleted it.Pamilapammi
V
425

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

Vickivickie answered 10/8, 2013 at 19:21 Comment(0)
M
349

There are two major approaches

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

     let fruits = ['Apple', 'Banana', 'Mango', 'Orange']
     let removed = fruits.splice(2, 1);
     // fruits is ['Apple', 'Banana', 'Orange']
     // removed is ['Mango']
    
  2. delete: delete anArray[index];

     let fruits = ['Apple', 'Banana', 'Mango', 'Orange']
     let removed = delete fruits(2);
     // fruits is ['Apple', 'Banana', undefined, 'Orange']
     // removed is true
    

Be careful when you use the 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 it wouldn't update the value of the 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, and 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.

Monson answered 21/12, 2012 at 11:32 Comment(1)
Can you delete a negative index in the case that the value is not in the array? example, delete array[array.indexOf(value)];Rudolf
S
280

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

var fruits = ['apple', 'banana', 'carrot', 'orange'];
fruits.removeByValue('banana');

console.log(fruits);
// -> ['apple', 'carrot', 'orange']
Stereochemistry answered 23/4, 2011 at 22:20 Comment(0)
S
206

There isn't any 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 Node.js for an array with 1000 elements (averaged over 10,000 runs):

indexof is approximately 10 times 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
Sharondasharos answered 19/9, 2013 at 1:53 Comment(0)
R
188

filter is an elegant way of achieving it without mutating the original array

const num = 3;
let arr = [1, 2, 3, 4];
const arr2 = arr.filter(x => x !== num);
console.log(arr); // [1, 2, 3, 4]
console.log(arr2); // [1, 2, 4]

You can use filter and then assign the result to the original array if you want to achieve a mutation removal behaviour.

const num = 3;
let arr = [1, 2, 3, 4];
arr = arr.filter(x => x !== num);
console.log(arr); // [1, 2, 4]

By the way, filter will remove all of the occurrences matched in the condition (not just the first occurrence) like you can see in the following example

const num = 3;
let arr = [1, 2, 3, 3, 3, 4];
arr = arr.filter(x => x !== num);
console.log(arr); // [1, 2, 4]

In case, you just want to remove the first occurrence, you can use the splice method

const num = 3;
let arr = [1, 2, 3, 3, 3, 4];
const idx = arr.indexOf(num);
arr.splice(idx, idx !== -1 ? 1 : 0);
console.log(arr); // [1, 2, 3, 3, 4]
Roseroseann answered 19/2, 2021 at 15:17 Comment(1)
pay attention that arr.splice(arr.indexOf(num), 1); has side effect, when number not found, it will delete 1 element from the array tailStillhunt
S
175

This provides a predicate instead of a value.

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

Usage

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

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

Definition

var helper = {
 // Remove and return the first occurrence

 remove: 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

 removeAll: 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;
 },
};
Secular answered 2/5, 2014 at 12:0 Comment(0)
P
151

You can do it easily with the 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 than a combination of slice and indexOf.

Peti answered 10/2, 2014 at 22:6 Comment(0)
A
140

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. I don't know why, but I confirmed John's original implementation doesn't have this problem.

Aubert answered 30/8, 2013 at 19:7 Comment(0)
R
135

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

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

Output :

["1", "2", "4", "5", "6"]
Rutaceous answered 4/10, 2016 at 8:7 Comment(1)
Note: Array.prototype.filter is ECMAScript 5.1 (No IE8). for more specific solutions: https://mcmap.net/q/32991/-how-can-i-remove-a-specific-item-from-an-array-in-javascriptVenterea
G
129

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]
Gooch answered 30/5, 2014 at 9:57 Comment(1)
though elegant and concise, OP clearly mentioned core JS onlyYasmineyasu
D
123

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

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

If you know the index of an item

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

One method is to use slice():

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

console.log(filteredItems)

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

If you know the value

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

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

console.log(filteredItems)

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

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

console.log(filteredItems)

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

Removing multiple items

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

Let's find the simplest solution.

By index

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

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

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

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

console.log(filteredItems)

By value

You can search for inclusion inside the callback function:

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

console.log(filteredItems)

Avoid mutating the original array

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

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

Disentomb answered 4/5, 2018 at 5:17 Comment(2)
Can you elaborate on why modifing the original array should be avoided? I'm iterating over an array in reverse order and want to either delete or keep the current element. After the loop I have only the kept elements left inside the array and can use it directly for the next operation. Your example would have me duplicate the array on every iteration. I could also create a new array and push all elements to keep into it, but wouldn't that be quite the memory overhead compared to my original approach?Louis
You can use filter with the index too: array.filter((el, idx) => idx !== index) returns an array without the item at index...Logographic
K
120

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 it's 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';}));

It should display [1, 2, 3, 4, 6].

Kern answered 18/10, 2012 at 10:13 Comment(1)
Why wouldn't you just filter out the value itself, or by index: my_array.filter(function(a, i) { return i !== 4;})? Don't mess with delete if you don't have to.Logographic
S
106

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

var array = [1,3,5,6,5,9,5,3,55]
var res = remove_item(array,5);
console.log(res)
Sensillum answered 2/4, 2013 at 10:56 Comment(2)
@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 ;)Bumpkin
I should also reiterate yckart's comment that for( i = 0; i < 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.Cruikshank
A
92

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

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

where:

theArray: the array you want to remove something particular from

stringToRemoveFromArray: the string you want to be removed and 1 is the number of elements you want to remove.

NOTE: If "stringToRemoveFromArray" is not located in the array, this will remove the last element of the array.

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

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

Depending if you have newer or older version of Ecmascript running on your client's computers:

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

OR

var array = ['1','2','3','4','5','6'];
var newArray = array.filter(function(item){ return item !== '3' });

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

Alphanumeric answered 8/1, 2019 at 14:34 Comment(1)
Beware, if "stringToRemoveFromArray" is not located your in array, this will remove last element of array.Freitas
P
89

ES10

This post summarizes common approaches to element removal from an array as of ECMAScript 2019 (ES10).

1. General cases

1.1. Removing Array element by value using .splice()

| In-place: Yes |
| Removes duplicates: Yes(loop), No(indexOf) |
| By value / index: By index |

If you know the value you want to remove from an array you can use the splice method. First, you must identify the index of the target item. You then use the index as the start element and remove just one element.

// With a 'for' loop
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
for( let i = 0; i < arr.length; i++){
  if ( arr[i] === 5) {
    arr.splice(i, 1);
  }
} // => [1, 2, 3, 4, 6, 7, 8, 9, 0]

// With the .indexOf() method
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
const i = arr.indexOf(5);
arr.splice(i, 1); // => [1, 2, 3, 4, 6, 7, 8, 9, 0]

1.2. Removing Array element using the .filter() method

| In-place: No |
| Removes duplicates: Yes |
| By value / index: By value |

The specific element can be filtered out from the array, by providing a filtering function. Such function is then called for every element in the array.

const value = 3
let arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(item => item !== value)
console.log(arr)
// [ 1, 2, 4, 5 ]

1.3. Removing Array element by extending Array.prototype

| In-place: Yes/No (Depends on implementation) |
| Removes duplicates: Yes/No (Depends on implementation) |
| By value / index: By index / By value (Depends on implementation) |

The prototype of Array can be extended with additional methods. Such methods will be then available to use on created arrays.

Note: Extending prototypes of objects from the standard library of JavaScript (like Array) is considered by some as an antipattern.

// In-place, removes all, by value implementation
Array.prototype.remove = function(item) {
    for (let i = 0; i < this.length; i++) {
        if (this[i] === item) {
            this.splice(i, 1);
        }
    }
}
const arr1 = [1,2,3,1];
arr1.remove(1) // arr1 equals [2,3]

// Non-stationary, removes first, by value implementation
Array.prototype.remove = function(item) {
    const arr = this.slice();
    for (let i = 0; i < this.length; i++) {
        if (arr[i] === item) {
            arr.splice(i, 1);
            return arr;
        }
    }
    return arr;
}
let arr2 = [1,2,3,1];
arr2 = arr2.remove(1) // arr2 equals [2,3,1]

1.4. Removing Array element using the delete operator

| In-place: Yes |
| Removes duplicates: No |
| By value / index: By index |

Using the delete operator does not affect the length property. Nor does it affect the indexes of subsequent elements. The array becomes sparse, which is a fancy way of saying the deleted item is not removed but becomes undefined.

const arr = [1, 2, 3, 4, 5, 6];
delete arr[4]; // Delete element with index 4
console.log( arr ); // [1, 2, 3, 4, undefined, 6]

The delete operator is designed to remove properties from JavaScript objects, which arrays are objects.

1.5. Removing Array element using Object utilities (>= ES10)

| In-place: No |
| Removes duplicates: Yes |
| By value / index: By value |

ES10 introduced Object.fromEntries, which can be used to create the desired Array from any Array-like object and filter unwanted elements during the process.

const object = [1,2,3,4];
const valueToRemove = 3;
const arr = Object.values(Object.fromEntries(
  Object.entries(object)
  .filter(([ key, val ]) => val !== valueToRemove)
));
console.log(arr); // [1,2,4]

2. Special cases

2.1 Removing element if it's at the end of the Array

2.1.1. Changing Array length

| In-place: Yes |
| Removes duplicates: No |
| By value / index: N/A |

JavaScript Array elements can be removed from the end of an array by setting the length property to a value less than the current value. Any element whose index is greater than or equal to the new length will be removed.

const arr = [1, 2, 3, 4, 5, 6];
arr.length = 5; // Set length to remove element
console.log( arr ); // [1, 2, 3, 4, 5]

2.1.2. Using .pop() method

| In-place: Yes |
| Removes duplicates: No |
| By value / index: N/A |

The pop method removes the last element of the array, returns that element, and updates the length property. The pop method modifies the array on which it is invoked, This means unlike using delete the last element is removed completely and the array length reduced.

const arr = [1, 2, 3, 4, 5, 6];
arr.pop(); // returns 6
console.log( arr ); // [1, 2, 3, 4, 5]

2.2. Removing element if it's at the beginning of the Array

| In-place: Yes |
| Removes duplicates: No |
| By value / index: N/A |

The .shift() method works much like the pop method except it removes the first element of a JavaScript array instead of the last. When the element is removed the remaining elements are shifted down.

const arr = [1, 2, 3, 4];
arr.shift(); // returns 1
console.log( arr ); // [2, 3, 4]

2.3. Removing element if it's the only element in the Array

| In-place: Yes |
| Removes duplicates: N/A |
| By value / index: N/A |

The fastest technique is to set an array variable to an empty array.

let arr = [1];
arr = []; //empty array

Alternatively technique from 2.1.1 can be used by setting length to 0.

Palmitate answered 2/4, 2020 at 10:15 Comment(0)
W
85

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']
Wester answered 25/8, 2015 at 19:34 Comment(2)
That's not core JS as the OP requested, is it?Annelieseannelise
@Annelieseannelise You are right. But a lot of users like me come here looking for a general answer not just for the OP only.Wester
A
84

ES6 & without mutation: (October 2016)

const removeByIndex = (list, index) =>
      [
        ...list.slice(0, index),
        ...list.slice(index + 1)
      ];
         
output = removeByIndex([33,22,11,44],1) //=> [33,11,44]
      
console.log(output)
Anosmia answered 7/10, 2016 at 19:42 Comment(1)
Why not just use filter then? array.filter((_, index) => index !== removedIndex);.Seaworthy
R
77

Performance

Today (2019-12-09) I conduct performance tests on macOS v10.13.6 (High Sierra) for chosen solutions. I show delete (A), but I do not use it in comparison with other methods, because it left empty space in the array.

The conclusions

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

Details

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

Results for an array with 10 elements

Enter image description here

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

Results for an array with 1.000.000 elements

Enter image description here

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

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

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

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

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

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

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

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

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

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

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

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

Enter image description here

Reservist answered 9/12, 2019 at 16:4 Comment(0)
A
62

OK, for example you have the array below:

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

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

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

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

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

But how about if you have the below array instead with a few [5]s in the array?

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

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

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

Also there are third-party libraries which do help you to do this, like Lodash or Underscore. For more information, look at lodash _.pull, _.pullAt or _.without.

Actinium answered 10/5, 2017 at 9:39 Comment(0)
I
60

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.

Ioab answered 16/1, 2014 at 11:27 Comment(2)
This is going to have terrible behavior if your array is really long and there are several instances of the element in it. The indexOf method of array will start at the beginning every time, so your cost is going to be O(n^2).Anglicism
@Zag: It has a name: Shlemiel the Painter's AlgorithmMetro
I
58

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

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

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

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

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

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

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

Ineradicable answered 30/10, 2018 at 17:37 Comment(0)
B
54

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]
Bloxberg answered 13/3, 2013 at 9:28 Comment(0)
Y
54

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

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

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

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

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

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

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

Yb answered 26/12, 2017 at 19:32 Comment(0)
C
53

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;
});
Centralize answered 9/4, 2015 at 10:0 Comment(1)
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.Bow
B
42

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);
}
console.log(myArray);
Bovine answered 12/8, 2013 at 17:56 Comment(0)
T
38

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.

Titi answered 25/4, 2016 at 10:21 Comment(6)
Note that .filter returns a new array, which is not exactly the same as removing the element from the same array. The benefit of this approach is that you can chain array methods together. eg: [1,2,3].filter(n => n%2).map(n => n*n) === [ 1, 9 ]Buffer
Great, if I have 600k elements in array and want to remove first 50k, can you imagine that slowness? This is not solution, there's need for function which just remove elements and returns nothing.Bridgettbridgette
@Seraph For that, you'd probably want to use splice or slice.Titi
@Titi Thats even better, in process of removal, just allocate 50K elements and throw them somewhere. (with slice 550K elements, but without throwing them from the window).Bridgettbridgette
I'd prefer bjfletcher's answer, which could be as short as items= items.filter(x=>x!=3). Besides, the OP didn't state any requirement for large data set.Animalist
The property Array.prototype.filter() is now fully supported, no need for babel or any polyfillThreonine
M
35

You have 1 to 9 in the array, and you want remove 5. Use the below code:

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

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

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

If you want to multiple values. Example:- 1,7,8

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

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

console.log("new Array, 1,7 and 8 removed", newNumberArray);

If you want to remove an array value in an array. Example: [3,4,5]

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

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

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

Includes supported browser is link.

Minority answered 7/8, 2018 at 9:37 Comment(0)
T
30
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');
Treasury answered 26/9, 2013 at 0:12 Comment(0)
L
30

An immutable and one-liner way:

const newArr = targetArr.filter(e => e !== elementToDelete);
Lautrec answered 2/6, 2020 at 16:18 Comment(1)
An important clarification for new programmers: This does not remove the target item from the array. It creates an entirely new array that is a copy of the original array, except with the target item removed.Towpath
V
28

Screenshot of demo

2021 UPDATE

Your question is about how to remove a specific item from an array. By specific item you are referring to a number eg. remove number 5 from array. From what I understand you are looking for something like:

// PSEUDOCODE, SCROLL FOR COPY-PASTE CODE
[1,2,3,4,5,6,8,5].remove(5) // result: [1,2,3,4,6,8]

As for 2021 the best way to achieve it is to use array filter function:

const input = [1,2,3,4,5,6,8,5];
const removeNumber = 5;
const result = input.filter(
    item => item != removeNumber
);

The above example uses array.prototype.filter function. It iterates over all array items, and returns only those satisfying the arrow function. As a result, the old array stays intact, while a new array called result contains all items that are not equal to five. You can test it yourself online.

You can visualize array.prototype.filter like this:

Animation visualizing array.prototype.filter

Considerations

Code quality

Array.prototype.filter is far the most readable method to remove a number in this case. It leaves little place for mistakes and uses core JS functionality.

Why not array.prototype.map?

Array.prototype.map is sometimes considered as an alternative for array.prototype.filter for that use case. But it should not be used. The reason is that array.prototype.filter is conceptually used to filter items that satisfy an arrow function (exactly what we need), while array.prototype.map is used to transform items. Since we don't change items while iterating over them, the proper function to use is array.prototype.filter.

Support

As of today (11.4.2022) 94,08% of Internet users' browsers support array.prototype.filter. So generally speaking it is safe to use. However, IE6 - 8 does not support it. So if your use case requires support for these browsers there is a nice polyfill made by Chris Ferdinanti.

Performance

Array.prototype.filter is great for most use cases. However if you are looking for some performance improvements for advanced data processing you can explore some other options like using pure for. Another great option is to rethink if the array you are processing really has to be so big. It may be a sign that the JavaScript should receive a reduced array for processing from the data source.

A benchmark of the different possibilities: https://jsben.ch/C5MXz

Verdie answered 2/12, 2020 at 11:21 Comment(1)
This is not "the best way to remove a specific item from an array". First off, .filter() removes ALL occurrences of removeNumber, not a specific entry. So in your example, if there were other elements of 5, they would also get removed, which is not what is wanted. Secondly, and closely tied to the first point, it's evaluating EVERY element in the array, so it's very inefficient if we know the index already. .filter() is evaluating every single element in the array with that condition.Brat
D
27

An immutable way of removing an element from an array using the ES6 spread operator.

Let's say you want to remove 4.

let array = [1,2,3,4,5]
const index = array.indexOf(4)
let new_array = [...array.slice(0,index), ...array.slice(index+1, array.length)]
console.log(new_array)
=> [1, 2, 3, 5]
Depreciate answered 31/5, 2020 at 11:58 Comment(1)
An important clarification for new programmers: This does not delete the target item from the array. It creates an entirely new array that is a copy of the original array, except with the target item removed. The word "delete" implies that we are mutating something in place, not making a modified copy.Towpath
V
26

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);
}
Vingtetun answered 3/2, 2014 at 15:41 Comment(2)
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.Vingtetun
But why a return in the middle? It is effectively a goto statement.Metro
M
25

I like this one-liner:

arr.includes(val) && arr.splice(arr.indexOf(val), 1)
  • ES6 (no Internet Explorer support)
  • Removal in done in-place.
  • Fast: no redundant iterations or duplications are made.
  • Support removing values such null or undefined

As a prototype

// remove by value. return true if value found and removed, false otherwise
Array.prototype.remove = function(val)
{
    return this.includes(val) && !!this.splice(this.indexOf(val), 1);
}

(Yes, I read all other answers and couldn't find one that combines includes and splice in the same line.)

Martyrology answered 5/4, 2021 at 16:16 Comment(2)
"immutable" means "not mutated" (i.e. returned value is not changing original value), in your case array is actually mutated.Beesley
@VictorGavro yes, but weirdly enough arrays are immutable even if their values are changed, as long as you don't change them into a new array. i know, it's weird for me too. i changed the phrasing in any case.Martyrology
C
24

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 Internet Explorer 8 (and later)):

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

Remove 1 element located at index from the array

my_array.splice(index, 1);
Chelsea answered 7/8, 2013 at 12:57 Comment(0)
B
24

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!

Boxthorn answered 28/1, 2014 at 14:44 Comment(0)
C
24

I tested splice and filter to see which is faster:

let someArr = [...Array(99999).keys()] 

console.time('filter')
someArr.filter(x => x !== 6666)
console.timeEnd('filter')

console.time('splice by indexOf')
someArr.splice(someArr.indexOf(6666), 1)
console.timeEnd('splice by indexOf')

On my machine, splice is faster. This makes sense, as splice merely edits an existing array, whereas filter creates a new array.

That said, filter is logically cleaner (easier to read) and fits better into a coding style that uses immutable state. So it's up to you whether you want to make that trade-off.

EDIT:

To be clear, splice and filter do different things: splice edits an array, whereas filter creates a new one. But either can be used to obtain an array with a given element removed.

Collocutor answered 6/4, 2021 at 22:55 Comment(1)
Re "splice is faster": Can you quantify that? How many times faster? Under what conditions (e.g., length/size of stuff. And on what system? Warm/cold? Etc.)? (But without "Edit:", "Update:", or similar - the answer should appear as if it was written today.)Metro
J
24

Using the array filter method:

let array = [1, 2, 3, 4, 511, 34, 511, 78, 88];

let value = 511;
array = array.filter(element => element !== value);
console.log(array)
Jota answered 24/4, 2021 at 19:3 Comment(2)
Very elegant solution! Even works if array elements are objects with properties, so you can do element.property !== valueReasoned
Can you link to the documentation for filter? (But without "Edit:", "Update:", or similar - the answer should appear as if it was written today.)Metro
D
24

I would like to club every possible solutions and rank it based on the performance. The one placed on top is more preferred to use than the last ones.

Consider this base case for all the methods:

let arr = [1, 2, 3, 4, 5];
let elementToRemove = 4;
let indexToRemove = arr.indexOf(elementToRemove);

  1. Using splice() method: [Best Approach / Efficient]
// When you don't know index
arr.splice(indexToRemove,1); // Remove a item at index of elementToRemove

// When you know index
arr.splice(3, 1); // Remove one item at index 3
console.log(arr); // Output: [1, 2, 3, 5]

  1. Using filter() method: [Good Approach]
let filteredArr = arr.filter((num) => num !== elementToRemove);
console.log(filteredArr); // Output: [1, 2, 3, 5]

  1. Using slice() method: [Longer Approach(Too much expressions)]
let newArr = arr.slice(0, indexToRemove).concat(arr.slice(indexToRemove + 1));
console.log(newArr); // Output: [1, 2, 3, 5]

  1. Using forEach() method: [Not recommended as it iterates through every element]
let newArr = [];
arr.forEach((num) => {
  if(num !== elementToRemove){
    newArr.push(num);
  }
});
console.log(newArr); // Output: [1, 2, 3, 5]
Dimension answered 1/3, 2023 at 11:42 Comment(1)
It's important to note that splice operates in-place so it's only the best approach if mutating the original array is what you want.Bibliotheca
C
23

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

Corycorybant answered 5/6, 2018 at 14:47 Comment(0)
E
22

I also ran into the situation where I had to remove an element from Array. .indexOf was not working in Internet Explorer, so I am sharing my working jQuery.inArray() solution:

var index = jQuery.inArray(val, arr);
if (index > -1) {
    arr.splice(index, 1);
    //console.log(arr);
}
Eakin answered 8/10, 2013 at 10:9 Comment(0)
H
20

Remove by Index

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

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

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

Remove by Value

Function that return a copy of array without the Value.

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

$> [ 1, 3, 4, 6, 7]
Hephzipa answered 12/5, 2017 at 2:0 Comment(1)
Are redundant constructions the norm around web developers? I have someone at work spraying stuff like this everywhere. Why not just return value != elem?!Lamblike
B
19

You can iterate over each array-item and splice it if it exists 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;
}
Bumpkin answered 13/5, 2013 at 12:22 Comment(1)
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.Sonde
A
17

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

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

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

Atul answered 13/4, 2019 at 8:51 Comment(3)
@codepleb, can you elaborate on why you prefer filter over splice and why you think filter is more readable?Dremadremann
Albeit not recommended for lengthy arrays.Pestilence
@Dremadremann Slice has a lot of options and they are confusing IMHO. You can, if you want, pass a start and end variable and while the start index is included, the end index is not, etc. It's harder to read code playing with slice. If you don't use that too often, you often end up checking the docs during reviews to check if something is correct. Docs: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Atul
C
15

In CoffeeScript:

my_array.splice(idx, 1) for ele, idx in my_array when ele is this_value
Crime answered 30/1, 2014 at 4:27 Comment(0)
F
15

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.

Fosterling answered 7/5, 2016 at 20:10 Comment(0)
T
15

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.

Tautog answered 8/5, 2017 at 17:58 Comment(2)
I like the idea, just think is a bit slow to do two stringify per element on the array. Anyway there are cases in which it will worth, thanks for sharing.Forzando
Thanks, I added an edit to clarify that valuesAreEqual can be substituted. I agree that the JSON approach is slow -- but it will always work. Should definitely use better comparison when possible.Tautog
E
15

Understand this:

You can use JavaScript arrays to group values and iterate over them. Array items can be added and removed in a variety of ways. There are 9 ways in total (use any of these which suits you). Instead of a delete method, the JavaScript array has a variety of ways you can clean array values.

Different techniques ways of doing this:

you can use it to remove elements from JavaScript arrays in these ways:

1-pop: Removes from the End of an Array.

2-shift: Removes from the beginning of an Array.

3-splice: removes from a specific Array index.

4- filter: this allows you to programmatically remove elements from an Array.


Method 1: Removing Elements from the Beginning of a JavaScript Array

var ar = ['zero', 'one', 'two', 'three'];
    
ar.shift(); // returns "zero"
    
console.log( ar ); // ["one", "two", "three"]

Method 2: Removing Elements from the End of a JavaScript Array

var ar = [1, 2, 3, 4, 5, 6];
    
ar.length = 4; // set length to remove elements
console.log( ar ); // [1, 2, 3, 4]


var ar = [1, 2, 3, 4, 5, 6];
    
ar.pop(); // returns 6
    
console.log( ar ); // [1, 2, 3, 4, 5]

Method 3: Using Splice to Remove Array Elements in JavaScript

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

var removed = arr.splice(2,2);
console.log(arr);


var list = ["bar", "baz", "foo", "qux"];
    
list.splice(0, 2); 
console.log(list);

Method 4: Removing Array Items By Value Using Splice

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    
    for( var i = 0; i < arr.length; i++){ 
    
        if ( arr[i] === 5) { 
    
            arr.splice(i, 1); 
        }
    
    }
    
    //=> [1, 2, 3, 4, 6, 7, 8, 9, 10]
    
    
var arr = [1, 2, 3, 4, 5, 5, 6, 7, 8, 5, 9, 10];
    
    for( var i = 0; i < arr.length; i++){ 
                                   
        if ( arr[i] === 5) { 
            arr.splice(i, 1); 
            i--; 
        }
    }

    //=> [1, 2, 3, 4, 6, 7, 8, 9, 10]

Method 5: Using the Array filter Method to Remove Items By Value

  var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    var filtered = array.filter(function(value, index, arr){ 
        return value > 5;
    });
    //filtered => [6, 7, 8, 9]
    //array => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Method 6: The Lodash Array Remove Method

var array = [1, 2, 3, 4];
var evens = _.remove(array, function(n) { 
                  return n % 2 === 0;
            });
            
console.log(array);// => [1, 3]console.log(evens);// => [2, 4]

Method 7: Making a Remove Method

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

function arrayRemove(arr, value) { 
    
        return arr.filter(function(ele){ 
            return ele != value; 
        });
    }
    
var result = arrayRemove(array, 6); // result = [1, 2, 3, 4, 5, 7, 8, 9, 10]

method 8: Explicitly Remove Array Elements Using the Delete Operator

var ar = [1, 2, 3, 4, 5, 6];
    
delete ar[4]; // delete element with index 4
    
console.log( ar ); // [1, 2, 3, 4, undefined, 6]
    
alert( ar ); // 1,2,3,4,,6

Method 9: Clear or Reset a JavaScript Array

var ar = [1, 2, 3, 4, 5, 6];
//do stuffar = [];
//a new, empty array!

var arr1 = [1, 2, 3, 4, 5, 6];
var arr2 = arr1; 
    // Reference arr1 by another variable arr1 = [];
    
console.log(arr2); 
// Output [1, 2, 3, 4, 5, 6]

var arr1 = [1, 2, 3, 4, 5, 6];
var arr2 = arr1; 
    // Reference arr1 by another variable arr1 = [];
    
console.log(arr2); 
// Output [1, 2, 3, 4, 5, 6]

Summary:

It's critical to manage your data by removing JavaScript Array items. Although there is no single "remove" function, you can purge unneeded array elements using a variety of ways and strategies.

Exhalation answered 4/2, 2022 at 3:38 Comment(1)
So this is a great answear but there is a suttle mistake. On method 4 if you had one 5 and right after another 5, what would happen is the first 5 would be deleted, changing the length of the array, and making the next 5 have the same index the other had, but as it increments the i value, the loop would keep going and leave the other 5 behind. You should do i--, to keep the loop on the next array item, or use a while loop that only increments the i value when it doesn't delete nothing.Tensor
L
14

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);
}
Limen answered 5/5, 2017 at 1:32 Comment(0)
E
14
[2,3,5].filter(i => ![5].includes(i))
Enthusiastic answered 24/4, 2019 at 4:32 Comment(0)
N
13

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.

Nf answered 17/9, 2014 at 10:14 Comment(2)
but OP said: "good ol' fashioned JavaScript - no frameworks allowed"Minutia
for Chrome 50.0, A.splice(-1, 1); will remove the last one in A.Equivocate
W
13

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 JavaScript 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 ECMAScript 6'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 ){
    // We have not seen this value before: make a 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.

Retrieving a modified int array from your "bucket object" is slightly involved but not so much: 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 (each is the unique index value in the original array): 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 JavaScript 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...)

Wolfram answered 24/11, 2017 at 19:17 Comment(0)
R
13

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

console.log(res)

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

developer.mozilla.org

Rask answered 15/2, 2018 at 8:14 Comment(1)
You better be sure you know the element is in the array, otherwise findindex returns -1 and consequently removes the 9.Multiplex
T
13

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

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

The splice() method

array.splice(index, 1);    

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

So for a single element, we use 1.

The delete method

delete array[index]

The filter() method

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

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

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

Tesstessa answered 5/2, 2019 at 5:34 Comment(0)
B
13

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

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

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

Beryllium answered 6/11, 2019 at 20:25 Comment(0)
S
13

In ES6, the Set collection provides a delete method to delete a specific value from the array, then convert the Set collection to an array by spread operator.

function deleteItem(list, val) {
    const set = new Set(list);
    set.delete(val);
    
    return [...set];
}

const letters = ['A', 'B', 'C', 'D', 'E'];
console.log(deleteItem(letters, 'C')); // ['A', 'B', 'D', 'E']
Sabol answered 14/8, 2020 at 19:11 Comment(0)
O
13

The simplest possible way to do this is probably using the filter function. Here's an example:

let array = ["hello", "world"]
let newarray = array.filter(item => item !== "hello");
console.log(newarray);
// ["world"]
Orlop answered 3/11, 2020 at 1:21 Comment(0)
S
12

You can use jQuery to help you!

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);
});
Slapstick answered 20/3, 2014 at 9:56 Comment(4)
Removes last item if searched item not foundArlindaarline
yes correct, you should know which element you want to remove like in the other examples.Slapstick
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"]Tarsia
@Dughall well, look at the jquery library and unpack it... and helpSupplejack
M
12

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;
}
Marra answered 22/10, 2014 at 14:10 Comment(1)
Your 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.Lammers
I
12

I 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();
}
Investment answered 30/7, 2017 at 22:55 Comment(0)
F
12

I found this blog post which is showing nine ways to do it:

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

I prefer to use filter():

var filtered_arr = arr.filter(function(ele){
   return ele != value;
})
Freethinker answered 9/1, 2020 at 9:54 Comment(2)
This doesn't remove the item from the array. It creates a brand new array with some items from the original array filtered out.Towpath
Yes it will return new array filtered. let me update codeFreethinker
G
12
 (function removeFromArrayPolyfill() {
      if (window.Array.prototype.remove) return;
    
      Array.prototype.remove = function (value) {
        if (!this.length || !value) return;
    
        const indexOfValue = this.indexOf(value);
    
        if (indexOfValue >= 0) {
          this.splice(indexOfValue, 1);
        }
      };
    })();
    
    // testing polyfill
    const nums = [10, 20, 30];
    nums.remove(20);
    console.log(nums);//[10,30]
Gladi answered 24/9, 2021 at 8:41 Comment(2)
Docs: removeFromArrayPolyfill: is an array method polyfill that takes in the value to be removed from an array. Note: This solution mustn't be a polyfill because the first rule to creating a polyfill is "Create a polyfill only when that feature is a released feature but hasn't been fully synchronized by browser engineers". So you can decide to make it a normal function instead that takes in the array and the value to be removed. Reason for this solution: The reason I made it a polyfill is due to how you called the remove.Gladi
An explanation would be in order. E.g., what is the idea/gist? How is it different from the other 136 answers? Please respond by changing your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today).Metro
J
12

The best way to remove an item from an array is to use the filter method. .filter() returns a new array without the filtered items.

items = items.filter(e => e.id !== item.id);

This .filter() method maps to a complete array and when I return the true condition, it pushes that current item to the filtered array. Read more on filter here.

Jonas answered 25/1, 2022 at 14:10 Comment(0)
C
11

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]
Carboniferous answered 29/1, 2016 at 8:53 Comment(0)
B
11

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;
}
Bybee answered 11/4, 2016 at 5:47 Comment(0)
P
11

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);
  }
};
Posting answered 12/8, 2016 at 17:59 Comment(1)
Also, no removeAt in ES standard. I suppose, this is some IE-only stuff? That should be mentioned in answer.Deel
A
11

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

/**
 * Removes one instance of `value` from `array`, without mutating the original array. Uses loose comparison.
 *
 * @param {Array} array Array to remove value from
 * @param {*} value Value to remove
 * @returns {Array} Array with `value` removed
 */
export function arrayRemove(array, value) {
    for(let i=0; i<array.length; ++i) {
        if(array[i] == value) {
            let copy = [...array];
            copy.splice(i, 1);
            return copy;
        }
    }
    return array;
}
Audun answered 9/4, 2017 at 20:9 Comment(3)
export const arrayRemove = (array, value) => [...array.filter(item => item !== value)]; Perhaps this could be simpler.Contractive
@Contractive Simpler, yes, but doesn't do exactly the same thing. Also don't think you need the [... -- .filter should already return a copy.Audun
@mpem My first impression was that could be a simpler way to do this but I agree is not doing the same thing. And yes the [... it is not needed in this case so even simpler :) thanks for that.Contractive
R
11

Non in-place solution

arr.slice(0,i).concat(arr.slice(i+1));

let arr = [10, 20, 30, 40, 50]

let i = 2 ; // position to remove (starting from 0)
let r = arr.slice(0,i).concat(arr.slice(i+1));

console.log(r);
Reservist answered 28/8, 2019 at 4:24 Comment(1)
What is the advantage of that?Metro
D
11

You can create an index with an all accessors example:

<div >
</div>

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


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

            }
        </ul>
    </fromList>

    <form id="form" method="post">
        <input  id="{this.accesors.id}">
        <input type="submit" callbackforApplySend...getIndex({this.accesors.id}) name="sendendform" value="removeIndex" >
    </form>
</div>
Dovelike answered 17/9, 2019 at 22:49 Comment(0)
R
11

Most of the answers here give a solution using -

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

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

Points to note about this solution -

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

The trick is to -

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

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

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

Check the remove method in the fiddle.

Roaster answered 2/10, 2019 at 7:36 Comment(2)
So, what exactly is the advantage of this method? What I see is that it's a terribly inefficient and error-prone method of performing a simple task. The result is not parsed again so it returns an array of strings instead of the input type. Even if it was parsed, on arrays of objects it would remove all function members. I don't see any good reason to ever do something like that but given that there are two people who thought this was a good idea, there must be something I'm missing.Quill
I agree with @StefanFabian, this is a terrible idea. What if my string is something like ",", that will replace all commas in the string version of the array. This is a terrible idea, and you should not do this.Marthamarthe
T
11

For removing only the first 34 from ages, not all the ages 34:

ages.splice(ages.indexOf(34), 1);

Or you can define a method globally:

function remove(array, item){
    let ind = array.indexOf(item);
    if(ind !== -1)
        array.splice(ind, 1);
}

For removing all the ages 34:

ages = ages.filter(a => a !== 34);
Thurston answered 9/5, 2022 at 12:28 Comment(3)
The first solution can be dangerous, as, if the element is not found, the last element of the array will be removed. This is because, when the element is not found, .indexOf will return -1 and using .splice(-1, 1) removes the last element.Mordvin
that doesn't matter. simple and ez answer.Selfforgetful
Why are you using != instead of !==?Elroyels
E
10

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>
Excavator answered 28/6, 2016 at 9:13 Comment(1)
The OP specifically said no frameworks. Hence the downvote.Anastasiaanastasie
M
10

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

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

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

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

// [1,3,4]

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

Monto answered 29/11, 2016 at 20:54 Comment(0)
S
10

I made a function:

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

And used it like this:

pop(valuetoremove, myarray);
Som answered 20/3, 2017 at 11:16 Comment(1)
If you're going to name it pop at least make it do what the method name implies!Sabec
P
10

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);
Passport answered 27/4, 2018 at 0:7 Comment(1)
Underrated answer. I was going to post it myself but had to look through the existing 132 answers to see if anyone had said it already. If you want to remove elements by value instead of position from a collection, then that collection should probably be a Set instead of an Array.Fosque
L
10

Delete an element from last

arrName.pop();

Delete an element from first

arrName.shift();

Delete from the middle

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

Example: arrName.splice(1, 1);

Delete one element from last

arrName.splice(-1);

Delete by using an array index number

 delete arrName[1];
Link answered 28/6, 2018 at 17:48 Comment(0)
D
10

You can use splice to remove objects or values from an array.

Let's consider an array of length 5, with values 10,20,30,40,50, and I want to remove the value 30 from it.

var array = [10,20,30,40,50];
if (array.indexOf(30) > -1) {
   array.splice(array.indexOf(30), 1);
}
console.log(array); // [10,20,40,50]
Dipterous answered 27/12, 2019 at 10:58 Comment(0)
L
10

If the array contains duplicate values and you want to remove all the occurrences of your target then this is the way to go...

let data = [2, 5, 9, 2, 8, 5, 9, 5];
let target = 5;
data = data.filter(da => da !== target);

Note: - the filter doesn't change the original array; instead it creates a new array.

So assigning again is important.

That's led to another problem. You can't make the variable const. It should be let or var.

Luddite answered 31/1, 2020 at 19:56 Comment(0)
T
10

This function removes an element from an array from a specific position.

array.remove(position);

Array.prototype.remove = function (pos) {
    this.splice(pos, 1);
}

var arr = ["a", "b", "c", "d", "e"];
arr.remove(2); // remove "c"
console.log(arr);

If you don't know the location of the item to delete use this:

array.erase(element);

Array.prototype.erase = function(el) {
    let p = this.indexOf(el); // indexOf use strict equality (===)
    if(p != -1) {
        this.splice(p, 1);
    }
}

var arr = ["a", "b", "c", "d", "e"];
arr.erase("c");
console.log(arr);
Treacle answered 16/1, 2021 at 21:55 Comment(0)
G
10

You could use the standard __proto__ of JavaScript and define this function. For example,

let data = [];
data.__proto__.remove = (n) => { data = data.flatMap((v) => { return v !== n ? v : []; }) };

data = [1, 2, 3];
data.remove(2);
console.log(data); // [1,3]

data = ['a','b','c'];
data.remove('b');
console.log(data); // [a,c]
Gerundive answered 25/6, 2021 at 4:39 Comment(0)
O
10
  1. Using indexOf, can find a specific index of number from array
    • using splice, can remove a specific index from array.

const array = [1,2,3,4,5,6,7,8,9,0];
const index = array.indexOf(5);
// find Index of specific number
if(index != -1){
    array.splice(index, 1); // remove number using index
}
console.log(array);
  1. To remove all occurrences.

let array = [1, 2, 3, 4, 5, 1, 7, 8, 9, 2, 3, 4, 5, 6];
array = array.filter(number=> number !== 5);
console.log(array);
  1. Using Join and split

    let array = [1, 2, 3, 4, 5, 1, 7, 8, 9, 2, 3, 4, 5, 6]
    array = Array.from(array.join("-").split("-5-").join("-").split("-"),Number)
    console.log(array)
Odoacer answered 3/3, 2022 at 6:33 Comment(0)
L
9

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
  }
}
Levin answered 10/1, 2016 at 13:36 Comment(0)
O
9

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://mcmap.net/q/28528/-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}]
Ousel answered 8/3, 2018 at 18:35 Comment(0)
B
9

A very naive implementation would be as follows:

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

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

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

Briefs answered 9/3, 2018 at 5:40 Comment(0)
D
9

Remove single element

function removeSingle(array, element) {
    const index = array.indexOf(element)
    if (index >= 0) {
        array.splice(index, 1)
    }
}

Remove multiple elements, in-place

This is more complicated to ensure the algorithm runs in O(N) time.

function removeAll(array, element) {
    let newLength = 0
    for (const elem of array) {
        if (elem !== number) {
            array[newLength++] = elem
        }
    }
    array.length = newLength
}

Remove multiple elements, creating new object

array.filter(elem => elem !== number)
Desberg answered 1/9, 2019 at 9:42 Comment(0)
S
9

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

Array.prototype.removeItem = function(array,val) {
    array.forEach((arrayItem,index) => {
        if (arrayItem == val) {
            array.splice(index, 1);
        }
    });
    return array;
}
var DummyArray = [1, 2, 3, 4, 5, 6];
console.log(DummyArray.removeItem(DummyArray, 3));
Saker answered 4/11, 2019 at 5:10 Comment(0)
S
9

Using .indexOf() and .splice() - Mutable Pattern

There are two scenarios here:

  1. we know the index

const drinks = [ 'Tea', 'Coffee', 'Milk'];
const id = 1;
const removedDrink = drinks.splice(id,  1);
console.log(removedDrink)
  1. we don’t know the index but know the value.
    const drinks =  ['Tea','Coffee', 'Milk'];
    const id = drinks.indexOf('Coffee'); // 1
    const removedDrink = drinks.splice(id,  1);
    // ["Coffee"]
    console.log(removedDrink);
    // ["Tea", "Milk"]
    console.log(drinks);

Using .filter() - Immutable Pattern

The best way you can think about this is - instead of “removing” the item, you’ll be “creating” a new array that just does not include that item. So we must find it, and omit it entirely.

const drinks = ['Tea','Coffee', 'Milk'];
const id = 'Coffee';
const idx = drinks.indexOf(id);
const removedDrink = drinks[idx];
const filteredDrinks = drinks.filter((drink, index) => drink == removedDrink);

console.log("Filtered Drinks Array:"+ filteredDrinks);
console.log("Original Drinks Array:"+ drinks);
Security answered 25/7, 2020 at 8:50 Comment(0)
P
9

If you're using a modern browser, you can use .filter.

Array.prototype.remove = function(x){
    return this.filter(function(v){
        return v !== x;
    });
};

var a = ["a","b","c"];
var b = a.remove('a');
Pelota answered 26/3, 2021 at 9:26 Comment(1)
Can you link to the documentation for filter? As a real link, not a naked link. (But without "Edit:", "Update:", or similar - the answer should appear as if it was written today).Metro
N
9

Try this code using the filter method and you can remove any specific item from an array.

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function removeItem(arr, value) {
  return arr.filter(function (ele) {
    return ele !== value;
  });
}
console.log(removeItem(arr, 6));
Nittygritty answered 19/4, 2021 at 8:10 Comment(0)
R
8

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;
}
Rodmun answered 18/9, 2017 at 13:17 Comment(0)
A
8

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

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

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

[1,2,3].remove(2).sort()
Ayeaye answered 21/12, 2018 at 15:10 Comment(0)
N
8

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

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

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

Nudi answered 19/12, 2019 at 9:5 Comment(1)
Perhaps qualify "all browsers"?Metro
S
8
  • pop - Removes from the End of an Array
  • shift - Removes from the beginning of an Array
  • splice - removes from a specific Array index
  • filter - allows you to programatically remove elements from an Array
Shanaeshanahan answered 25/11, 2020 at 14:27 Comment(0)
Z
8
const arr = [1, 2, 3, 4, 5]
console.log(arr) // [ 1, 2, 3, 4, 5 ]

Suppose you want to remove number 3 from arr.

const newArr = arr.filter(w => w !==3)
console.log(newArr) // [ 1, 2, 4, 5 ]
Zadoc answered 18/10, 2022 at 16:31 Comment(0)
P
7
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.

Poult answered 25/6, 2014 at 23:57 Comment(1)
This is very inefficient when the array is large.Usquebaugh
T
7

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;
Thanh answered 7/1, 2015 at 19:53 Comment(0)
E
7

The splice() function is able to give you back an item in the array as well as remove item / items from a specific index:

function removeArrayItem(index, array) {
    array.splice(index, 1);
    return array;
}

let array = [1,2,3,4];
let index = 2;
array = removeArrayItem(index, array);
console.log(array);
Ervinervine answered 8/11, 2020 at 13:50 Comment(1)
Can you link to the documentation for splice? (But without "Edit:", "Update:", or similar - the answer should appear as if it was written today.)Metro
I
7

There are many ways to remove a specific element from a JavaScript array. The following are the 5 best available methods I could came up with in my research.

1. Using 'splice()' method directly

In the following code segment, elements in a specific pre-determined location is/are removed from the array.

  • syntax: array_name.splice(begin_index,number_of_elements_remove);
  • application:

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

console.log("Original array: " + arr);

var removed = arr.splice(4, 2);

console.log("Modified array: " + arr);

console.log("Elements removed: " + removed);

2. Remove elements by 'value' using 'splice()' method

In the following code segment we can remove all the elements equal to a pre-determined value (ex: all the elements equal to value 6) using a if condition inside a for loop.

var arr = [1, 2, 6, 3, 2, 6, 7, 8, 9, 10];

console.log("Original array: " + arr);

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

  if (arr[i] === 6) {

    var removed = arr.splice(i, 1);
    i--;
  }

}

console.log("Modified array: " + arr); // 6 is removed
console.log("Removed elements: " + removed);

3. Using the 'filter()' method remove elements selected by value

Similar to the implementation using 'splice()' method, but instead of mutating the existing array, it create a new array of elements having removed the unwanted element.

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

var filtered = array.filter(function(value, index, arr) {
  return value != 6 ;
});

console.log("Original array: "+array);

console.log("New array created: "+filtered); // 6 is removed

4. Using the 'remove()' method in 'Lodash' JavaScript library

In the following code segment, there remove() method in the JavaScript library called 'Lodash'. This method is also similar to the filter method.

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log("Original array: " + array);

var removeElement = _.remove(array, function(n) {
  return n === 6;
});

console.log("Modified array: " + array);
console.log("Removed elements: " + removeElement); // 6 is removed
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

5. making a custom remove method

There is no native 'array.remove' method in JavaScript, but we can create one using above methods we used as implemented in the following code snippet.

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

function arrayRemove(arr, value) {

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

console.log("Original array: " + array);
console.log("Modified array: " + arrayRemove(array, 6)); // 6 is removed

The final method (number 5) is more appropriate for solving the above issue.

Illustrious answered 9/3, 2021 at 13:32 Comment(0)
B
7

You can add a prototype function to "remove" the element from the array.

The following example shows how to simply remove an element from an array, when we know the index of the element. We use it in the Array.filter method.

Array.prototype.removeByIndex = function(i) {
    if(!Number.isInteger(i) || i < 0) {
        // i must be an integer
        return this;
    }

    return this.filter((f, indx) => indx !== i)
}
var a = [5, -89, (2 * 2), "some string", null, false, undefined, 20, null, 5];

var b = a.removeByIndex(2);
console.log(a);
console.log(b);

Sometimes we don't know the index of the element.

Array.prototype.remove = function(i) {
    return this.filter(f => f !== i)
}
var a = [5, -89, (2 * 2), "some string", null, false, undefined, 20, null, 5];

var b = a.remove(5).remove(null);
console.log(a);
console.log(b);

// It removes all occurrences of searched value

But, when we want to remove only the first occurrence of the searched value, we can use the Array.indexOf method in our function.

Array.prototype.removeFirst = function(i) {
    i = this.indexOf(i);

    if(!Number.isInteger(i) || i < 0) {
        return this;
    }

    return this.filter((f, indx) => indx !== i)
}
var a = [5, -89, (2 * 2), "some string", null, false, undefined, 20, null, 5];

var b = a.removeFirst(5).removeFirst(null);
console.log(a);
console.log(b);
Birch answered 20/9, 2021 at 14:32 Comment(0)
D
7

There are multiple ways to do it, and it’s up to you how you want it to act.

One approach is to use the splice method and remove the item from the array:

let array = [1, 2, 3]
array.splice(1, 1);
console.log(array)

// return [1, 3]

But make sure you pass the second argument or you end up deleting the whole array after the index.

The second approach is to use the filter method and the benefit with it is that it is immutable which means your main array doesn't get manipulated:

const array = [1, 2, 3];
const newArray = array.filter(item => item !== 2)
console.log(newArray)

// return [1, 3]
Drove answered 11/3, 2022 at 15:44 Comment(0)
P
7

This is my simple code to remove specific data in an array using the splice method. The splice method will be given two parameters. The first parameter is the start number, and the second parameter is deleteCount. The second parameter is used for removing some element start from the value of the first parameter.

let arr = [1, 3, 5, 6, 9];

arr.splice(0, 2);

console.log(arr);
Pretypify answered 10/5, 2022 at 15:57 Comment(1)
What do you mean by "...removing some element start from the value"? It seems incomprehensible. Please respond by editing (changing) your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today).Metro
Q
6

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

Quarterphase answered 26/11, 2014 at 19:39 Comment(2)
While 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.Munniks
Sadly, 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.Quarterphase
C
6

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>
Commissioner answered 15/11, 2015 at 11:9 Comment(2)
What is meaning of this code I could not understand.Hildahildagard
@AnkurLoriya This code removes all 0s from the given arrayCommissioner
A
6

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

Use splice() method to fulfill your requirement.

Please have a look at the below code.

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

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

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

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

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

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

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

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

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

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

To remove a particular element or subsequent elements, Array.splice() method works well.

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements, and it returns the removed item(s).

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

Here index is mandatory and rest arguments are optional.

For example:

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

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

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

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

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

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

    Or by using the splice() method as:

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

    Or suppose we want to delete del from the array arr:

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

    Or

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

    let arr = [1, 11, 2, 11, 3, 4, 5, 11, 6, 11];
    
    for (let i = 0; i < arr.length-1; i++) {
      if ( arr[i] === 11) {
        arr.splice(i, 1);
        break;
      }
    }
    console.log(arr);
    // [1, 11, 2, 11, 3, 4, 5, 11, 6, 11]
    
Venterea answered 27/1, 2019 at 16:55 Comment(2)
Note: Array.prototype.filter is ECMAScript 5.1 (No IE8)Venterea
For option 4, should the loop be 'i < arr.length' not 'i < arr.length-1'?Frozen
M
6

The cleanest of all :

var arr = ['1','2','3'];
arr = arr.filter(e => e !== '3');
console.warn(arr);

This will also delete duplicates (if any).

Mastiff answered 12/1, 2022 at 6:47 Comment(0)
K
5

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.

Kunkel answered 12/9, 2018 at 9:16 Comment(1)
OP asked about removing a particular (one) element from an array. This function does not terminate when one element is found but keeps comparing every single element in the array until the end is reached.Kunkel
K
5

You just need filter by element or index:

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

var result1 = num.filter((el, index) => el != 5) // for remove all 5
var result2 = num.filter((el, index) => index != 5) // for remove item with index == 5

console.log(result1);
console.log(result2);
Kif answered 27/1, 2021 at 20:10 Comment(0)
P
5

You can use a Set instead and use the delete function:

const s = Set;
s.add('hello');
s.add('goodbye');
s.delete('hello');
Playwright answered 4/11, 2021 at 3:10 Comment(0)
P
4

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

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

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

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

// Expected output;
// array before delete 1,2,4,4,5,3,45,9
// array after delete 2,4,4,5,3,45,9
Pacien answered 23/8, 2019 at 12:20 Comment(1)
Note that this function will live only as long as the numbers array. If you create a new array, you'll need to add the delete function to it as well.Logographic
H
4

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

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

console.log(arr)

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

Hypersonic answered 18/9, 2019 at 10:57 Comment(0)
S
4
  1. Get the array and index
  2. From arraylist with array elements
  3. Remove the specific index element using remove() method
  4. From the new array of the array list using maptoint() and toarray() method
  5. Return the formatted array
Sarnoff answered 13/11, 2021 at 7:4 Comment(0)
J
4
const newArray = oldArray.filter(item => item !== removeItem);
Jerrold answered 16/6, 2022 at 1:57 Comment(1)
An explanation would be in order. E.g., how is it different from other answers? This seems like a rip-off of many previous answers (that do have explanations). E.g., Ali Raza's answer (which may or may not in itself be a repeat answer). E.g., what is the point of the source array being different from the destination array? Something FP? Please respond by editing (changing) your question, not here in comments (without "Edit:" or "Update:").Metro
M
4

The two fastest ways that I love to use to remove an element from an array:

  1. Remove only the first element using the splice method
  2. Remove all elements which match in the array using a for loop

const heartbreakerArray = ["😂","❤️","😍","❤️","❤️"]


// 1. If you want to remove only the first element from the array
const shallowCopy = Array.from(heartbreakerArray)
const index = shallowCopy.indexOf("❤️")
if (index > -1) { shallowCopy.splice(index, 1) }

console.log(shallowCopy) // Array(2) ["😂","😍","❤️","❤️"]


// 2. If you want to remove all matched elements from the array
const myOutputArray = []
const mySearchValue = "❤️"
for(let i = 0; i < heartbreakerArray.length; i++){
  if(heartbreakerArray[i]!==mySearchValue) {
    myOutputArray.push(heartbreakerArray[i])
  }
}

console.log(myOutputArray) // Array(2) ["😂","😍"]

You can read the detailed blog post The fastest way to remove a specific item from an array in JavaScript.

Monoplegia answered 6/9, 2022 at 8:45 Comment(1)
The code comment "remove each element of the array" does not seem to match the code.Metro
K
3
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;
}
Karilla answered 21/5, 2016 at 4:8 Comment(0)
T
3

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("!@#").split("!@#4!@#").join("!@#").split("!@#");
console.log(out);
Titled answered 14/7, 2017 at 23:58 Comment(2)
You can see that there are strings in the second example I provided? I am not sure what you mean by this? The only issue is if your string contains one of the charterers used in the separation, as I mentioned in my answer.Titled
Interesting method, you can use Unicode characters for splitting (e.g. '\uD842') instead. For making it clearer and shorter for others, I'd just add a few more strings to the array elements (including '4') and take out the first snippet/example (people may have downvoted because they didn't even read the 2nd part).Bedspread
T
3
    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]

Traver answered 22/7, 2018 at 4:42 Comment(1)
this may collide with other code, libraries, i would rather implement a remove function for that specific arrayPacien
S
3
var arr =[1,2,3,4,5];

arr.splice(0,1)

console.log(arr)

Output [2, 3, 4, 5];

Slung answered 31/12, 2018 at 23:33 Comment(0)
S
3

Take profit of reduce method as follows:

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

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

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

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

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

Scatter answered 2/2, 2019 at 14:41 Comment(0)
R
3

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

If you do want an empty slot:

array[index] = undefined;

If you don't want an empty slot:

To keep the original:

oldArray = [...array];

This modifies the array.

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

If you want to remove at either end of the array, you can use array.pop() for the last one or array.shift() for the first one (both return the value of the item as well).

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.

Restrainer answered 14/12, 2021 at 13:36 Comment(0)
F
3

In case you want to remove several items, I found this to be the easiest:

const oldArray = [1, 2, 3, 4, 5]
const removeItems = [1, 3, 5]

const newArray = oldArray.filter((value) => {
    return !removeItems.includes(value)
})

console.log(newArray)

Output:

[2, 4]
Fidget answered 10/5, 2022 at 8:36 Comment(0)
C
3

Simple. Just do it:

var arr = [1,2,4,5];
arr.splice(arr.indexOf(5), 1);
console.log(arr); // [1,2,4];
Circumambient answered 18/7, 2022 at 12:1 Comment(0)
C
3

You can simply add remove function to array protoType

something like this :

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

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

let array = [10,15,20]

result = array.remove(10)
console.log(result)
Collado answered 6/12, 2022 at 10:42 Comment(0)
V
2

Lodash:

let a1 = {name:'a1'}
let a2 = {name:'a2'}
let a3 = {name:'a3'}
let list = [a1, a2, a3]
_.remove(list, a2)
//list now is [{name: "a1"}, {name: "a3"}]

Check this for details: .remove(array, [predicate=.identity])

Violette answered 22/12, 2021 at 8:54 Comment(0)
O
2

Beside all this solutions it can also be done with array.reduce...

const removeItem = 
    idx => 
    arr => 
    arr.reduce((acc, a, i) =>  idx === i ? acc : acc.concat(a), [])

const array = [1, 2, 3]
const index = 1

const newArray = removeItem(index)(array) 

console.log(newArray) // logs the following array to the console : [1, 3]

... or a recursive function (which is to be honest not that elegant...has maybe someone a better recursive solution ??)...

const removeItemPrep = 
    acc => 
    i => 
    idx => 
    arr => 

    // If the index equals i, just feed in the unchanged accumulator(acc) else...
    i === idx ? removeItemPrep(acc)(i + 1)(idx)(arr) :

    // If the array length + 1 of the accumulator is smaller than the array length of the original array concatenate the array element at index i else... 
    acc.length + 1 < arr.length ? removeItemPrep(acc.concat(arr[i]))(i + 1)(idx)(arr) : 

    // return the accumulator
    acc 

const removeItem = removeItemPrep([])(0)

const array = [1, 2, 3]
const index = 1

const newArray = removeItem(index)(array) 

console.log(newArray) // logs the following array to the console : [1, 3]
Olympias answered 2/2, 2022 at 11:52 Comment(0)
L
2
function array_remove(arr, index) {
    for (let i = index; i < arr.length - 1; i++) {
        arr[i] = arr[i + 1];
    }
    arr.length -= 1;
    return arr;
}
my_arr = ['A', 'B', 'C', 'D'];
console.log(array_remove(my_arr, 0));
Lucrecialucretia answered 5/2, 2022 at 10:22 Comment(1)
Could you provide some explanation?Coequal
S
2

Filter with different types of array

    **simple array**
    const arr = ['1','2','3'];
    const updatedArr = arr.filter(e => e !== '3');
    console.warn(updatedArr);

    **array of object**
    const newArr = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}]
    const updatedNewArr = newArr.filter(e => e.id !== 3);
    console.warn(updatedNewArr);

    **array of object with different parameter name**
    const newArr = [{SINGLE_MDMC:{id:1,cout:10}},{BULK_MDMC:{id:1,cout:15}},{WPS_MDMC:{id:2,cout:10}},]
    const newArray = newArr.filter((item) => !Object.keys(item).includes('SINGLE_MDMC'));
    console.log(newArray)
Signorina answered 18/2, 2022 at 5:57 Comment(0)
F
2

If you want a [...].remove(el)-like syntax, like other programming languages, then you can add this code:

// Add remove method to Array prototype
Array.prototype.remove = function(value, count=this.length) {
    while(count > 0 && this.includes(value)) {
        this.splice(this.indexOf(value), 1);
        count--;
    }
    return this;
}

Usage

// Original array
const arr = [1,2,2,3,2,5,6,7];

// Remove all 2s from array
arr.remove(2); // [1,3,5,6,7]

// Remove one 2 from beginning of array
arr.remove(2, 1); // [1,2,3,2,5,6,7]

// Remove two 2s from beginning of array
arr.remove(2, 2); // [1,3,2,5,6,7]

You can manipulate the method as per your need.

Fireball answered 13/11, 2022 at 11:33 Comment(0)
C
2

I found another way to remove specific item from array
In the below example, I am removing "2" from the list.

1. If Array contains duplicate values, e.g., [1,2,3,4,2,2,1,1,2]

var arr = [1,2,3,4,2,2,1,1,2];
console.log(arr.filter((e)=>e!=2));

2. If Array doesn't contain duplicate value eg. [1,2,3,4,5]

var arr = [1,2,3,4];
arr.splice(arr.indexOf(2),1);
console.log(arr);
Chorizo answered 1/8, 2023 at 15:57 Comment(0)
H
2

There are two major approaches to solve this problem:

Utility Function (recommended):

You could write an utility function to remove an item from an array:

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


const arr = ['apple', 'banana', 'grape', 'kiwi', 'apple', 'orange', 'banana'];
console.log(removeItem(arr, 'banana'));

// ['apple', 'grape', 'kiwi', apple', orange', 'banana']

You could see in the above code snippet, it only removes one match item (i.e. 'banana') and to remove all matching items from an array, you could try the following:

function removeAllItems(arr, value) {
  let i = 0;
  
  while (i < arr.length) {
    if (arr[i] === value) {
      arr.splice(i, 1);
    } else {
      ++i;
    }
  }
  
  return arr;
}

const arr = ['apple', 'banana', 'grape', 'kiwi', 'apple', 'orange', 'banana'];
console.log(removeAllItems(arr, 'banana'));

// ['apple', 'grape', 'kiwi', apple', orange']

Updating Array Prototype:

You could also add a function to the Array object's prototype chain, which removes all the matching items:

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

const arr = ['apple', 'banana', 'grape', 'kiwi', 'apple', 'orange', 'banana'];
arr.removeByValue('banana');
console.log(arr);

// ['apple', 'grape', 'kiwi', apple', orange']
Halfwit answered 14/3 at 12:40 Comment(0)
H
1

Definition:

function RemoveEmptyItems(arr) {
  var result = [];
  for (var i = 0; i < arr.length; i++) if (arr[i] != null && arr[i].length > 0) result.push(arr[i]);
  return result;
}

Usage:

var arr = [1,2,3, "", null, 444];
arr = RemoveEmptyItems(arr);
console.log(arr);
Huh answered 27/12, 2021 at 13:25 Comment(0)
B
1

To remove an item by passing its value-

const remove=(value)=>{
    myArray = myArray.filter(element=>element !=value);

}

To remove an item by passing its index number -

  const removeFrom=(index)=>{
    myArray = myArray.filter((_, i)=>{
        return i!==index
    })
}
Baltazar answered 14/6, 2022 at 2:16 Comment(0)
S
1

You can do this task in many ways in JavaScript

  1. If you know the index of the value: in this case you can use splice

    var arr = [1,2,3,4]
    // Let's say we have the index, coming from some API
    let index = 2;
    // splice is a destructive method and modifies the original array
    arr.splice(2, 1)
    
  2. If you don't have the index and only have the value: in this case you can use filter

    // Let's remove '2', for example
    arr = arr.filter((value)=>{
        return value !== 2;
    })
    
Sarabia answered 16/6, 2022 at 4:59 Comment(0)
B
1

In JavaScript, you can use the Array.prototype.filter() method to remove a specific value from an array.

Here's an example:

let array = [1, 2, 3, 4, 5];
let value = 3;

array = array.filter(function(element) {
  return element !== value;
});

console.log(array); // Output: [1, 2, 4, 5]

In the above code, we first create an array and define the value that we want to remove. Then we use the filter() method to create a new array that includes only the elements that are not equal to the given value. Finally, we assign the new array back to the original array variable.

Note that the filter() method creates a new array instead of modifying the original array. If you want to modify the original array directly, you can use a for loop to iterate over the array and remove the element at the given index.

Here's an example:

let array = [1, 2, 3, 4, 5];
let value = 3;

for (let i = 0; i < array.length; i++) {
  if (array[i] === value) {
    array.splice(i, 1);
    i--; // decrement i since the array has been modified
  }
}

console.log(array); // Output: [1, 2, 4, 5]

In this example, we use a for loop to iterate over the array and check if each element is equal to the given value. If it is, we use the splice() method to remove the element at the current index. Since the splice() method modifies the original array, we decrement i to ensure that we check the next element in the updated array.

Bughouse answered 27/2, 2023 at 18:35 Comment(0)
W
1

I do like this.

const arr = ["apple", "banana", "orange", "pear", "grape"];

const itemToRemove = "orange";

const filteredArr = arr.filter(item => item !== itemToRemove);

console.log(filteredArr); // ["apple", "banana", "pear", "grape"]
Waterlogged answered 18/4, 2023 at 2:51 Comment(0)
M
1

If you want to create a new array instead of modifying the original array in place, use Array.prototype.toSpliced():

const index = array.indexOf(value);
const newArray = array.toSpliced(index, 1);
Monochromatic answered 8/7, 2023 at 12:35 Comment(0)
R
0

For example, you have a characters array and want to delete "A" from the array.

The array has a filter method which can filter and return only those elements that you want.

let CharacterArray = ['N', 'B', 'A'];

I want to return elements apart from 'A'.

CharacterArray = CharacterArray.filter(character => character !== 'A');

Then CharacterArray must be: ['N', 'B']

Rue answered 14/7, 2022 at 5:37 Comment(0)
R
0
let removeAnElement = (arr, element)=>{
    let findIndex = -1;
    for (let i = 0; i<(arr.length); i++){
        if(arr[i] === element){
            findIndex = i;
            break;
        }
    }
    if(findIndex == -1){
        return arr;
    }
    for (let i = findIndex; i<(arr.length-1); i++){
        arr[i] =  arr[i+1];
    }
    arr.length -= 1;
    return arr;
}

let array = ['apple', 'ball', 'cat', 'dog', 'egg'];
let removeElement = 'ball';

let tempArr2 = removeAnElement(array, 'dummy');
console.log(tempArr2);
// ['apple', 'cat', 'dog', 'egg']

let tempArr = removeAnElement(array, removeElement);
console.log(tempArr);`enter code here`
// ['apple', 'cat', 'dog', 'egg']
Rattlebrain answered 19/12, 2022 at 10:7 Comment(1)
This is using code JS. You can do the same work with more simple code. It is with core concept which can use in almost all languages with a few changes.Rattlebrain
J
0
const arr = [2, 3, 1, 6];
const _index = arr.indexOf(3);
if (_index > -1) { // _index>-1 only when item exists in the array
  arr.splice(_index, 1);
}
Jarry answered 18/6, 2023 at 6:51 Comment(0)
A
0

Using filter(): The filter() method creates a new array with all elements that pass a certain condition.

You can use it to filter out the specific item you want to remove. Here's an example:

const array = [1, 2, 3, 4, 5];
const itemToRemove = 3;

const filteredArray = array.filter(item => item !== itemToRemove);
console.log(filteredArray); 

// Output: [1, 2, 4, 5]
Apollonian answered 27/6, 2023 at 17:38 Comment(0)
C
0

If you want to avoid modifying the original array directly, use Array.prototype.toSpliced(). Nevertheless, please be mindful of its limited browser support at present.

const stocks = ["Microsoft", "Nvidia", "Amazon"]
const copy = stocks.toSpliced(0, 1, "Alphabet")

console.log("Copy", copy)
console.log("Original", stocks)
Cute answered 29/7, 2023 at 9:29 Comment(0)
C
0

I've provided four ways to remove an item from an array.

splice(): removes an item with a specified index.

filter(): removes an item with a specified value.

pop(): removes the item at the end of the array.

shift(): removes the item at the start of the array.

I've created a snippet to demonstrate each of these specific methods.

let simpleArray = [1, 2, 3, 4, 5];
document.getElementById('result').innerText = `Simple Array: ${simpleArray}`;

// Remove by index using splice()
function removeByIndexSplice(array) {
  let indexToRemove = parseInt(document.getElementById('indexToRemoveSplice').value);

  array.splice(indexToRemove, 1);

  document.getElementById('result').innerText = `Array after removal: ${array}`;
}

// Remove by value using filter()
function removeByValueFilter(array) {
  let valueToRemove = parseInt(document.getElementById('valueToRemoveFilter').value);

  array = array.filter(item => item !== valueToRemove);

  document.getElementById('result').innerText = `Array after removal: ${array}`;
}

// Remove last item using pop()
function removeLastItemPop(array) {
  array.pop();

  document.getElementById('result').innerText = `Array after removal: ${array}`;
}

// Remove first item using shift()
function removeFirstItemShift(array) {
  array.shift();

  document.getElementById('result').innerText = `Array after removal: ${array}`;
}
body {
  display: flex;
  flex-flow: column nowrap;
}
<!DOCTYPE html>
<html>

<body>
  <h1>Simple ways to remove an item from an Array</h1>
  <div>
  <h2>splice()</h2>
    <label for="indexToRemoveSplice">Enter index to Remove:</label>
    <input type="number" id="indexToRemoveSplice">
    <button onclick="removeByIndexSplice(simpleArray)">Remove Item</button>
  </div>
  <div>
  <h2>filter()</h2>
    <label for="valueToRemoveFilter">Enter value to Remove:</label>
    <input type="number" id="valueToRemoveFilter">
    <button onclick="removeByValueFilter(simpleArray)">Remove Item</button>
  </div>
  <div>
  <h2>pop()</h2>
    <button onclick="removeLastItemPop(simpleArray)">Remove Last Item</button>
  </div>
  <div>
  <h2>shift()</h2>
    <button onclick="removeFirstItemShift(simpleArray)">Remove First Item</button></div>
  <p id="result"></p>
</body>

</html>
Catarina answered 14/12, 2023 at 17:0 Comment(0)
S
0

const items = [1, 3, 2, 4];
const value = 2;
const filteredItems = items.filter(item => item !== value);
console.log(filteredItems); // Output: [1, 3, 4]
Sideshow answered 22/12, 2023 at 7:41 Comment(0)
C
0

Easiest Way to to that :

const array = [2,5,6,7,8,9];
const index = array.indexOf(5);
if (index > -1) { // only splice array when item is found
  array.splice(index, 1); // 2nd parameter means remove one item only
}

// array = [2,6,7,8,9]
console.log(array);
Crest answered 10/1 at 20:56 Comment(0)
T
0

I just used 'Array slice()' method:

const letterArray = ["a", "b", "c", "d", "e", "f"];//let's remove letter 'c'

const letterRemoval = letterArray.slice(0, 2);//this gives us new array ['a', 'b']

const joinArray = letterRemoval.concat(letterArray.slice(3));//let's merge two new arrays together

console.log(joinArray);
Theaterintheround answered 8/3 at 5:28 Comment(0)
K
-1

I made these methods as extension methods for Array-type objects, you can add them to your codes and use them like native Array methods.

if (!Array.prototype.removeItem) {
    Object.defineProperty(Array.prototype, 'removeItem', {
        /**
         * Removing first instance of specified item by @value from array
         * @param {any} value
         * @returns
         */
        value: function (value) {
            var index = this.indexOf(value);
            if (index > -1)
                this.splice(index, 1);
            return this;
        }
    });
}

if (!Array.prototype.removeIndex) {
    Object.defineProperty(Array.prototype, 'removeIndex', {
        /**
         * Removing item at @index
         * @param {int} index
         * @returns
         */
        value: function (index) {
            if (index > -1)
                this.splice(index, 1);
            return this;
        }
    });
}

if (!Array.prototype.removeItems) {
    Object.defineProperty(Array.prototype, 'removeItems', {
        /**
         * Removing all items like @value .\n
         * If @value is null this function will removes all items
         * @param {any} value
         * @returns
         */
        value: function (value) {
            if (value == null)
                return [];
            else {
                let i = 0;
                while (i < this.length) {
                    if (this[i] === value)
                        this.splice(i, 1);
                    else
                        ++i;
                }
            }
            return this;
        }
    });
}
Kantor answered 10/7, 2023 at 9:21 Comment(2)
While this would work, adding to js prototypes is generally discouraged as you can end up with conflicts with libraries that also brazenly modify prototypes. flaviocopes.com/javascript-why-not-modify-object-prototypeHudnall
Yes, you are right, we can change the name of the functions to some other names to prevent this case you mentionedKantor
B
-1

You can filter out with array.filter.

const arr=['a','b','c','d','e']
const newArray = arr.filter(v => v!='a');
console.log(newArray); // ['b', 'c', 'd', 'e']

Or you could remove several items

const newArray = arr.filter(v => !['a', 'b'].some(t => t == a));
console.log(newArray) // ['c', 'd', 'e']
Belongings answered 15/12, 2023 at 1:15 Comment(0)
K
-1
  1. Will create a copy of the original array:

    array.filter(num => num !== valueToRemove);

  2. Using filter and reasigning to the original array will maintain the same reference:

    array = array.filter(num => num !== valueToRemove);

  3. Using indexOf changes the contents of original array without creating a new array.

    array.splice(indexOf(valueToRemove), 1);

All three options have a time complexity of O(n).

Koralle answered 15/12, 2023 at 17:58 Comment(0)
F
-2

Try to remove the array element using the delete operator

For an instance:

const arr = [10, 20, 30, 40, 50, 60];
delete arr[2]; // It will Delete element present at index 2
console.log( arr ); // [10, 20, undefined , 40, 50, 60]

Note: Using delete operator will leave empty spaces/ holes in an array. It will not alert the length of an array. To change the length of an array when the element is deleted from it, use splice method instead.

Hope this could resolve all your problems.

Fanchie answered 21/1, 2022 at 17:49 Comment(0)
P
-2

There are two main scenarios:

  • you want to remove the first occurrence
  • you want to remove all occurrences

Remove first occurrence

let array = ['a', 'b', 'c', 'd', 'c', 'e', 'f', 'g'];
array = array.filter((item, ind) => (ind != array.indexOf('c')));
console.log(array);

We simply find the index of c and filter that out. Of course, in order to speed things up, we could compute .indexOf just before the .filter() call.

Remove all occurrences

let array = ['a', 'b', 'c', 'd', 'c', 'e', 'f', 'g'];
array = array.filter(item => (item !== 'c'));
console.log(array);
Pejsach answered 6/8, 2023 at 13:44 Comment(2)
Small note: one needs to call 'array.indexOf' first outside the loop to optimize: let array = ['a', 'b', 'c', 'd', 'c', 'e', 'f', 'g']; const indexOfC = array.indexOf('c'); array = array.filter((item, ind) => (ind != indexOfC)); console.log(array);Arango
@Arango that's known. I have also mentioned it in my answer (which was already there prior to the down-vote): "Of course, in order to speed things up, we could compute .indexOf just before the .filter() call.". Yet, I kept the code very simple for the sake of understandability. But thanks for the comment!Pejsach
B
-3

You can use

Array.splice(index);
Beggarweed answered 28/1, 2020 at 12:4 Comment(2)
Your code remove all elements after index. For remove 1 element at index 3 you can use Array.splice(index, 1).Ascidium
if you wanna remove just one element using splice you have to create 2 array one from first element to previous element and one from next element to end. and concat or merge that arrays with spread .Kif

© 2022 - 2024 — McMap. All rights reserved.