11614

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.

Muhammad Asadullah
  • 3,735
  • 1
  • 22
  • 38
Walker
  • 128,495
  • 27
  • 68
  • 94
  • 54
    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! – Gustavo Gonçalves Oct 24 '20 at 15:51
  • 2
    Anyone checking this question, do see the problems associated with using `delete` for arrays mentioned by Sasa – Vaulstein Nov 26 '21 at 08:10
  • 9
    @Gustavo Gonçalves I do not understand the problem: the [opposite of `Array#push()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop) is well-known. (Of course, that is not what this question is asking for.) – Brian Drake Feb 03 '22 at 13:29
  • Just use Jquery /s – stickynotememo Jul 19 '23 at 11:51

150 Answers150

16359

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;
}
Kewal Shah
  • 1,131
  • 18
  • 29
Tom Wadley
  • 121,983
  • 1
  • 26
  • 29
  • 713
    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.) – default123 Sep 10 '20 at 00:16
  • 1
    @default123 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/delete – Andrew Nov 23 '20 at 22:48
  • 28
    @Andrew sets and arrays are two completely different collection types. – Stefan Fabian Dec 01 '20 at 09:44
  • 9
    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)} } – Luke Dupin Dec 08 '20 at 22:30
  • 9
    function remove(item,array) { var new_array = [] new_ array = array.filter((ar)=> ar != item) return new_array } – Rashid Iqbal Jan 07 '21 at 16:04
  • 2
    Return statement is misleading. Array is already modified. It can confuse that origin array will be untouched. – mikep Mar 23 '21 at 12:08
  • 1
    `Array.pull()` is what humankind needs the most. – deb Apr 08 '21 at 16:03
  • 15
    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? xD – OOPS Studio Apr 15 '21 at 09:12
  • @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 element – Eve Apr 12 '22 at 21:05
  • 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 deletion – Kewal Shah Jun 29 '22 at 01:55
  • 6
    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 improved – Christian Vincenzo Traina Jul 22 '22 at 08:06
  • If only json supported sets, then we could use sets instead :( – GreenAsJade Aug 02 '22 at 22:49
  • How to remove value from array with the value, not the index? –  Aug 11 '22 at 16:20
  • @CodemasterUnited `array.splice(array.indexOf("value"), 1)` – code Oct 01 '22 at 21:30
  • 1
    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://stackoverflow.com/q/42681148/1066234 "it returns what was removed, but the array is empty" – Avatar Nov 11 '22 at 11:22
  • Use the `.findIndex(o => o.property === valueToCompare)` method to get an index of an object from the array. – Arsen Khachaturyan Nov 21 '22 at 19:56
  • hi i have array '{62 => 105, 59 => 3.33}' i wnat to delete 59 and its value how i can do that – Hamza Qureshi Jan 29 '23 at 17:48
  • @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? @Eve 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. – Md. A. Apu Mar 20 '23 at 15:40
  • 2
    **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 `= undefined` – jave.web Mar 22 '23 at 14:27
  • TY, these functions – G.D.i Apr 07 '23 at 11:01
  • @jave.web 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 =D – Mike 'Pomax' Kamermans Jun 07 '23 at 14:51
  • @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. – jave.web Jun 07 '23 at 22:27
  • 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. – Mike 'Pomax' Kamermans Jun 07 '23 at 22:34
2377

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

Caveman
  • 2,527
  • 1
  • 17
  • 18
ujeenator
  • 26,384
  • 2
  • 23
  • 28
1729

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];
Lioness100
  • 8,260
  • 6
  • 18
  • 49
Peter Olson
  • 139,199
  • 49
  • 202
  • 242
  • 4
    `delete array[i]` would degrade the performance of the application and is considered a bad pratice – Christian Vincenzo Traina Jul 22 '22 at 08:09
  • 9
    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. – Heretic Monkey Aug 05 '22 at 20:20
  • 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. – Slbox Nov 20 '22 at 02:34
656

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. 

Andrew
  • 5,839
  • 1
  • 51
  • 72
xavierm02
  • 8,457
  • 1
  • 20
  • 24
  • 4
    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. – Teddy Jul 25 '20 at 10:55
  • 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. – Mike 'Pomax' Kamermans Jun 07 '23 at 14:59
407

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.

Ben Lesh
  • 107,825
  • 47
  • 247
  • 232
329

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.

Saša
  • 4,416
  • 1
  • 27
  • 41
264

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']
flosommerfeld
  • 634
  • 2
  • 11
  • 23
Zirak
  • 38,920
  • 13
  • 81
  • 92
190

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
slosd
  • 3,224
  • 2
  • 21
  • 17
163

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;
 },
};
amd
  • 20,637
  • 6
  • 49
  • 67
161

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]
Ran Turner
  • 14,906
  • 5
  • 47
  • 53
140

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.

Masoud Aghaei
  • 775
  • 7
  • 20
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
128

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Roger
  • 2,118
  • 1
  • 20
  • 25
124

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"]
darmis
  • 2,879
  • 1
  • 19
  • 21
rajat44
  • 4,941
  • 6
  • 29
  • 37
  • 1
    Note: Array.prototype.filter is ECMAScript 5.1 (No IE8). for more specific solutions: https://stackoverflow.com/a/54390552/8958729 – Chang Jan 27 '19 at 19:45
118

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]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
vatsal
  • 3,803
  • 2
  • 19
  • 19
112

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

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Flavio Copes
  • 4,131
  • 4
  • 27
  • 30
  • 1
    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? – harlekintiger Jun 26 '22 at 20:17
  • You can use `filter` with the index too: `array.filter((el, idx) => idx !== index)` returns an array without the item at `index`... – Heretic Monkey Aug 05 '22 at 20:34
111

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Loupax
  • 4,728
  • 6
  • 41
  • 68
  • 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. – Heretic Monkey Aug 05 '22 at 20:31
97

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)
Masoud Aghaei
  • 775
  • 7
  • 20
Ekramul Hoque
  • 4,957
  • 3
  • 30
  • 31
  • 5
    @RolandIllig Except the use of a `for in`-loop and the fact that the script could stopped earlier, by returning the result from the loop directly. The upvotes are reasonable ;) – yckart Dec 30 '14 at 16:13
  • 1
    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. – Beejor Aug 21 '16 at 23:20
83

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

Max Alexander Hanna
  • 3,388
  • 1
  • 25
  • 35
  • 6
    Beware, if `"stringToRemoveFromArray"` is not located your in array, this will remove last element of array. – Fusion Apr 06 '19 at 23:35
80

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
M. Twarog
  • 2,418
  • 3
  • 21
  • 39
78

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

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

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

var array3 = ['i', 'j', 'k', 'l']
var newArray = _.without(array3, 'i') // ['j', 'k', 'l']
console.log(array3) // ['i', 'j', 'k', 'l']
Chun Yang
  • 2,451
  • 23
  • 16
77

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)
dipenparmar12
  • 3,042
  • 1
  • 29
  • 39
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
70

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

Ammar
  • 73
  • 6
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
55

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alireza
  • 100,211
  • 27
  • 269
  • 172
53

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.

yckart
  • 32,460
  • 9
  • 122
  • 129
sofiax
  • 559
  • 4
  • 3
  • 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). – Zag May 24 '19 at 18:22
  • @Zag: It has a name: [Shlemiel the Painter's Algorithm](http://www.joelonsoftware.com/articles/fog0000000319.html) – Peter Mortensen Sep 01 '19 at 22:11
51

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.

tagurit
  • 494
  • 5
  • 13
AmerllicA
  • 29,059
  • 15
  • 130
  • 154
49

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


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

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

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

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

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

    return destroyed;
}

Usage:

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

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

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

x.destroy(3);         // => null
x;                    // => [1, 2]
zykadelic
  • 1,083
  • 11
  • 19
48

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.

Community
  • 1
  • 1
Adeel Imran
  • 13,166
  • 8
  • 62
  • 77
47

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

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

this.array = this.array.filter(function(element, i) {
    return element.id !== idToRemove;
});
flurdy
  • 3,782
  • 29
  • 31
  • This is how I like to do it. Using an arrow function it can be a one-liner. I'm curious about performance. Also worth nothing that this *replaces* the array. Any code with a reference to the *old array* will not notice the change. – joeytwiddle Jul 29 '16 at 08:50
38

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);
Jeff Noel
  • 7,500
  • 4
  • 40
  • 66
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.

tagurit
  • 494
  • 5
  • 13
bjfletcher
  • 11,168
  • 4
  • 52
  • 67
  • 4
    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 ]` – CodeOcelot May 06 '16 at 18:58
  • 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. – dev1223 May 30 '16 at 15:11
  • @Seraph For that, you'd probably want to use `splice` or `slice`. – bjfletcher May 31 '16 at 22:04
  • @bjfletcher 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). – dev1223 May 31 '16 at 23:06
  • 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. – runsun Aug 27 '16 at 01:55
  • The property `Array.prototype.filter()` is now fully supported, no need for babel or any polyfill – jadinerky Aug 09 '22 at 23:07
34

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.

Thilina Sampath
  • 3,615
  • 6
  • 39
  • 65
31
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');
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
30

An immutable and one-liner way:

const newArr = targetArr.filter(e => e !== elementToDelete);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
katma
  • 311
  • 3
  • 3
  • 2
    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. – Daniel Waltrip Jul 07 '20 at 00:20
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

EscapeNetscape
  • 2,892
  • 1
  • 33
  • 32
Tom Smykowski
  • 25,487
  • 54
  • 159
  • 236
  • 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. – Dan Jan 13 '21 at 01:55
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]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ahmad
  • 1,497
  • 2
  • 9
  • 16
  • 8
    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. – Daniel Waltrip Jul 07 '20 at 00:21
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);
}
wharding28
  • 1,271
  • 11
  • 13
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.)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
oriadam
  • 7,747
  • 2
  • 50
  • 48
  • "immutable" means "not mutated" (i.e. returned value is not changing original value), in your case array is actually mutated. – Victor Gavro Apr 28 '21 at 16:17
  • @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. – oriadam Jun 08 '21 at 12:20
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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Enrico
  • 623
  • 10
  • 26
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!

Ardi
  • 338
  • 2
  • 4
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)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
shweta ghanate
  • 281
  • 2
  • 4
  • Very elegant solution! Even works if array elements are objects with properties, so you can do `element.property !== value` – Larphoid May 01 '21 at 22:31
  • Can you [link](https://stackoverflow.com/posts/67246473/edit) to the documentation for `filter`? (But ***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today.) – Peter Mortensen Jan 02 '22 at 16:16
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

cela
  • 2,352
  • 3
  • 21
  • 43
Aram Grigoryan
  • 740
  • 1
  • 6
  • 24
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);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Smile
  • 2,770
  • 4
  • 35
  • 57
22

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.

Asker
  • 1,299
  • 2
  • 14
  • 31
  • 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.) – Peter Mortensen Jan 02 '22 at 16:18
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]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
nsantana
  • 1,992
  • 1
  • 16
  • 17
  • Are redundant constructions the norm around web developers? I have someone at work spraying stuff like this everywhere. Why not just `return value != elem`?! – Buffalo Jul 24 '17 at 11:59
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;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
yckart
  • 32,460
  • 9
  • 122
  • 129
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
codepleb
  • 10,086
  • 14
  • 69
  • 111
  • @codepleb, can you elaborate on why you prefer filter over splice and why you think filter is more readable? – MHOOS Jun 20 '19 at 09:47
  • Albeit not recommended for lengthy arrays. – eightyfive Jun 20 '19 at 10:07
  • 1
    @MHOOS Slice has a lot of options and they are confusing IMHO. You can, if you want, pass a start and end variable and while the start index is included, the end index is not, etc. It's harder to read code playing with slice. If you don't use that too often, you often end up checking the docs during reviews to check if something is correct. Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice – codepleb Jun 26 '19 at 16:12
16

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]
krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88
  • 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. – Adam Hughes May 23 '23 at 18:39
15

In CoffeeScript:

my_array.splice(idx, 1) for ele, idx in my_array when ele is this_value
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Redu
  • 25,060
  • 6
  • 56
  • 76
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.

Aidan Hoolachan
  • 2,285
  • 1
  • 11
  • 14
  • 1
    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. – Adriano Spadoni Jul 25 '17 at 08:56
  • 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. – Aidan Hoolachan Oct 07 '17 at 20:33
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.

Vihan Gammanpila
  • 346
  • 4
  • 10
Muhammad Ali
  • 956
  • 3
  • 15
  • 20
  • 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. – Osmar Apr 25 '22 at 17:47
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);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
alejandro
  • 2,799
  • 1
  • 17
  • 25
14
[2,3,5].filter(i => ![5].includes(i))
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Do Hoa Vinh
  • 356
  • 4
  • 11
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...)

mike rodent
  • 14,126
  • 11
  • 103
  • 157
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

Masoud Aghaei
  • 775
  • 7
  • 20
Sujith S
  • 555
  • 5
  • 8
  • 2
    You better be sure you know the element is in the array, otherwise findindex returns -1 and consequently removes the 9. – pwilcox Jul 29 '18 at 14:44
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.

Arun s
  • 869
  • 9
  • 19
Ashish
  • 2,026
  • 17
  • 19
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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Taylor Hawkes
  • 641
  • 7
  • 10
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']
Abdelrhman Arnos
  • 1,404
  • 3
  • 11
  • 22
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"]
Coding
  • 325
  • 2
  • 5
  • 12
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;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nejc Lepen
  • 357
  • 3
  • 5
  • 15
    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. – ylerjen Oct 22 '14 at 14:43
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();
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
hailong
  • 1,409
  • 16
  • 19
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;
})
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ravi Makwana
  • 2,782
  • 1
  • 29
  • 41
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]
Emmanuel Onah
  • 580
  • 4
  • 8
  • 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. – Emmanuel Onah Sep 24 '21 at 08:48
  • 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](https://stackoverflow.com/posts/69312035/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Jan 02 '22 at 16:09
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.

Evaa
  • 283
  • 1
  • 2
  • 15
Ali Raza
  • 1,026
  • 13
  • 20
11

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);
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mboeckle
  • 938
  • 13
  • 29
  • Removes last item if searched item not found – Hontoni Apr 30 '14 at 17:05
  • 2
    yes correct, you should know which element you want to remove like in the other examples. – mboeckle May 01 '14 at 17:00
  • 5
    This is jQuery, not core JavaScript. – Dughall Apr 18 '16 at 15:31
  • any other way for some repeated value max 5 times then create new array and remove that value from array? I HAVE THIS KIND OF ARRAY: ["info.specificAllergy", "info.specificAllergy", "info.specificAllergy", "info.specificAllergy", "info.specificAllergy", "info.existingMedicalCondition", "info.existingMedicalCondition", "info.existingMedicalCondition", "info.existingMedicalCondition", "info.existingMedicalCondition"] – Jignesh Vagh Jul 14 '17 at 14:22
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]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kamuran Sönecek
  • 3,293
  • 2
  • 30
  • 57
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;
}
Lars Gyrup Brink Nielsen
  • 3,939
  • 2
  • 34
  • 35
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);
  }
};
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shawn Deprey
  • 467
  • 8
  • 27
  • Also, no `removeAt` in ES standard. I suppose, this is some IE-only stuff? That should be mentioned in answer. – ankhzet Jun 19 '18 at 09:01
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;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • `export const arrayRemove = (array, value) => [...array.filter(item => item !== value)];` Perhaps this could be simpler. – darmis Oct 01 '19 at 21:04
  • @darmis Simpler, yes, but doesn't do exactly the same thing. Also don't think you need the `[...` -- `.filter` should already return a copy. – mpen Oct 01 '19 at 23:05
  • @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. – darmis Oct 02 '19 at 07:21
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);
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pritam
  • 2,452
  • 1
  • 21
  • 31
  • 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. – Stefan Fabian Mar 13 '20 at 13:38
  • 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. – mausworks Mar 24 '21 at 15:38
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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Weilory
  • 2,621
  • 19
  • 35
  • 6
    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. – Napoleon May 13 '22 at 07:10
  • that doesn't matter. simple and ez answer. – JaeIL Ryu May 19 '22 at 08:12
  • Why are you using `!=` instead of `!==`? – Neil Jun 18 '22 at 14:08
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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mahendra Kulkarni
  • 1,437
  • 2
  • 26
  • 35
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().

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Stelios Voskos
  • 526
  • 5
  • 17
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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ali Akram
  • 4,803
  • 3
  • 29
  • 38
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);
Steven Spungin
  • 27,002
  • 5
  • 88
  • 78
  • 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. – ArtOfWarfare Oct 04 '21 at 02:21
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];
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Srikrushna
  • 4,366
  • 2
  • 39
  • 46
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]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Arun s
  • 869
  • 9
  • 19
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ifelse.codes
  • 2,289
  • 23
  • 21
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);
Blackjack
  • 1,322
  • 1
  • 16
  • 21
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]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Julio Vinachi
  • 381
  • 4
  • 8
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)
Sahil Thummar
  • 1,926
  • 16
  • 16
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
  }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MEC
  • 1,690
  • 1
  • 17
  • 23
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://stackoverflow.com/questions/948358/adding-custom-functions-into-array-prototype
  Object.defineProperty(Array.prototype, 'remove', {
    value: function () {
      if (this == null) {
        throw new TypeError('Array.prototype.remove called on null or undefined')
      }

      for (var i = 0; i < arguments.length; i++) {
        if (typeof arguments[i] === 'object') {
          if (Object.keys(arguments[i]).length > 1) {
            throw new Error('This method does not support more than one key:value pair per object on the arguments')
          }
          var keyToCompare = Object.keys(arguments[i])[0]

          for (var j = 0; j < this.length; j++) {
            if (this[j][keyToCompare] === arguments[i][keyToCompare]) {
              this.splice(j, 1)
              break
            }
          }
        } else {
          var index = this.indexOf(arguments[i])
          if (index !== -1) {
            this.splice(index, 1)
          }
        }
      }
      return this
    }
  })
} else {
  var errorMessage = 'DANGER ALERT! Array.prototype.remove has already been defined on this browser. '
  errorMessage += 'This may lead to unwanted results when remove() is executed.'
  console.log(errorMessage)
}

Removing an integer value

var a = [1, 2, 3]
a.remove(2)
a // Output => [1, 3]

Removing a string value

var a = ['a', 'ab', 'abc']
a.remove('abc')
a // Output => ['a', 'ab']

Removing a boolean value

var a = [true, false, true]
a.remove(false)
a // Output => [true, true]

It is also possible to remove an object inside the array via this Array.prototype.remove method. You just need to specify the key => value of the Object you want to remove.

Removing an object value

var a = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 3, b: 2}]
a.remove({a: 1})
a // Output => [{a: 2, b: 2}, {a: 3, b: 2}]
Victor
  • 1,904
  • 18
  • 18
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().

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gaurang Patel
  • 459
  • 5
  • 11
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)
Konrad Borowski
  • 11,584
  • 3
  • 57
  • 71
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));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ajay Thakur
  • 1,066
  • 7
  • 23
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);
karthicvel
  • 343
  • 2
  • 5
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');
Dishant Chanchad
  • 710
  • 3
  • 9
  • 27
  • 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). – Peter Mortensen Jan 02 '22 at 16:21
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));
phwt
  • 1,356
  • 1
  • 22
  • 42
Force Bolt
  • 1,117
  • 9
  • 9
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;
}
cjjenkinson
  • 359
  • 4
  • 7
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()
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sebastien H.
  • 6,818
  • 2
  • 28
  • 36
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

Josh
  • 670
  • 7
  • 14
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
Tijo John
  • 686
  • 1
  • 9
  • 20
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 ]
James Risner
  • 5,451
  • 11
  • 25
  • 47
Harsh Rathod
  • 129
  • 1
  • 4
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.

penguin
  • 724
  • 5
  • 11
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;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ryan
  • 3,153
  • 2
  • 23
  • 35
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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MSA
  • 249
  • 5
  • 10
  • Can you link to the documentation for `splice`? (But ***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today.) – Peter Mortensen Jan 02 '22 at 16:28
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/lodash@4.17.21/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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pawara Siriwardhane
  • 1,873
  • 10
  • 26
  • 38
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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jnbm
  • 118
  • 2
  • 4
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]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
amir yeganeh
  • 647
  • 3
  • 11
  • 23
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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • What do you mean by *"...removing some element start from the value"*? It seems incomprehensible. Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/72189536/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Sep 04 '22 at 14:14
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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Matt Brock
  • 5,337
  • 1
  • 27
  • 26
  • 3
    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. – sampathsris May 18 '15 at 03:03
  • 1
    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. – Matt Brock May 18 '15 at 13:38
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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Eugene Tiurin
  • 4,019
  • 4
  • 33
  • 32
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
>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
hygull
  • 8,464
  • 2
  • 43
  • 52
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]
    
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chang
  • 435
  • 1
  • 8
  • 17
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).

shekhar chander
  • 600
  • 8
  • 14
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Phil
  • 1,062
  • 1
  • 17
  • 15
  • 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. – Phil Sep 18 '19 at 05:18
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);
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Masoud Aghaei
  • 775
  • 7
  • 20
5

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

const s = Set;
s.add('hello');
s.add('goodbye');
s.delete('hello');
k26dr
  • 1,229
  • 18
  • 15
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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mekbib.awoke
  • 1,094
  • 1
  • 9
  • 16
  • 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. – Heretic Monkey Jul 07 '20 at 17:29
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.

Masoud Aghaei
  • 775
  • 7
  • 20
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
Nimantha
  • 6,405
  • 6
  • 28
  • 69
4
const newArray = oldArray.filter(item => item !== removeItem);
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
user6689187
  • 101
  • 3
  • 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](https://stackoverflow.com/a/70850094) (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](https://en.wikipedia.org/wiki/Functional_programming)? Please respond by [editing (changing) your question](https://stackoverflow.com/posts/72639648/edit), not here in comments (***without*** "Edit:" or "Update:"). – Peter Mortensen Sep 04 '22 at 14:10
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.

Robin Hossain
  • 711
  • 9
  • 12
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;
}
Oss
  • 4,232
  • 2
  • 20
  • 35
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);
Partial Science
  • 330
  • 2
  • 6
  • 1
    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. – Partial Science Jul 20 '17 at 19:33
  • 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). – CPHPython Feb 19 '18 at 16:25
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]

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Zibri
  • 9,096
  • 3
  • 52
  • 44
3
var arr =[1,2,3,4,5];

arr.splice(0,1)

console.log(arr)

Output [2, 3, 4, 5];

Machavity
  • 30,841
  • 27
  • 92
  • 100
Shahriar Ahmad
  • 149
  • 1
  • 3
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.

alejoko
  • 993
  • 8
  • 14
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.

jiwopene
  • 3,077
  • 17
  • 30
Enrico König
  • 206
  • 1
  • 13
  • 22
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]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Artur Müller Romanov
  • 4,417
  • 10
  • 73
  • 132
3

Simple. Just do it:

var arr = [1,2,4,5];
arr.splice(arr.indexOf(5), 1);
console.log(arr); // [1,2,4];
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aslam khan
  • 315
  • 1
  • 7
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)
Ali Sattarzadeh
  • 3,220
  • 1
  • 6
  • 20
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])

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
guogangj
  • 2,275
  • 3
  • 27
  • 44
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]
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));
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
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)
Aayush Bhattacharya
  • 1,628
  • 18
  • 17
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Partha Maity
  • 90
  • 1
  • 7
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);
Erçin Dedeoğlu
  • 4,950
  • 4
  • 49
  • 69
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
    })
}
navinrangar
  • 904
  • 10
  • 20
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;
    })
    
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Himanshu Jangid
  • 369
  • 4
  • 15
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.

Tharindu Lakshan
  • 3,995
  • 6
  • 24
  • 44
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"]
Zia
  • 506
  • 3
  • 20
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);
Géry Ogam
  • 6,336
  • 4
  • 38
  • 67
1

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);
Tiwari
  • 45
  • 2
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']

Hkachhia
  • 4,463
  • 6
  • 41
  • 76
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']
  • 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. – Shakil Abdus Shohid Dec 19 '22 at 10:09
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);
}
dilipkumar1007
  • 329
  • 4
  • 22
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]
elwin013
  • 519
  • 10
  • 19
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)
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
-1
 const Delete = (id) => {
      console.log(id)
     var index = Array.map(function(e){
      return e.id;
     
     }).indexOf(id);
     Array.splice(index,1);
     
}
Lekhraj
  • 455
  • 4
  • 9
-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;
        }
    });
}
user229044
  • 232,980
  • 40
  • 330
  • 338
Sayed Abolfazl Fatemi
  • 3,678
  • 3
  • 36
  • 48
-2

You can use

Array.splice(index);
Dharman
  • 30,962
  • 25
  • 85
  • 135
Janardan Prajapati
  • 119
  • 1
  • 1
  • 8
  • 3
    Your code remove all elements after index. For remove 1 element at index 3 you can use Array.splice(index, 1). – Majid Savalanpour Jun 14 '20 at 09:47
  • 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 . – Masoud Aghaei Feb 02 '21 at 19:47
-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.

Rahul Daksh
  • 212
  • 1
  • 7
-2

fuction findData=(itemid)=>{

 let SelectedDataIndex = SelectedData.findIndex(i => i.id == itemid) 
        if (SelectedDataIndex > -1) {
          
            SelectedData.splice(SelectedDataIndex, 1)
        } 

}

  • Answer needs supporting information Your answer could be improved with additional supporting information. Please [edit](https://stackoverflow.com/posts/76217628/edit) to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](https://stackoverflow.com/help/how-to-answer). – moken May 12 '23 at 11:41
-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);
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • 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);``` – Ashot Aug 07 '23 at 06:11
  • @Ashot 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! – Lajos Arpad Aug 07 '23 at 09:26
-22
let array = [5,5,4,4,2,3,4]    
let newArray = array.join(',').replace('5','').split(',')

This example works if you want to remove one current item.

sampathsris
  • 21,564
  • 12
  • 71
  • 98