9441

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

Is there a simple way to remove a specific element from an array?

I'm looking for the equivalent of something like:

array.remove(number);

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

Melanie Shebel
  • 2,449
  • 6
  • 27
  • 49
Walker
  • 104,797
  • 22
  • 64
  • 92
  • 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
  • For those who don't want `indexOf()` + `splice()`: 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:49
  • Opposite of push is pop – EnderShadow8 Mar 27 '21 at 05:14

109 Answers109

13679

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) {
  array.splice(index, 1);
}

// array = [2, 9]
console.log(array); 

The second parameter of splice is the number of elements to remove. Note that splice modifies the array in place and returns a new array containing the elements that have been removed.


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;
}
a2br
  • 745
  • 1
  • 4
  • 17
Tom Wadley
  • 122,421
  • 1
  • 22
  • 29
  • 184
    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
  • @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
  • 6
    @Andrew sets and arrays are two completely different collection types. – Stefan Fabian Dec 01 '20 at 09:44
  • @StefanFabian Yes, they are, but in many many cases they will be interchangeable. – Andrew Dec 01 '20 at 21:08
  • 2
    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
  • 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
  • Remove all elements: const array = [2, 5, 9]; array.length = 0; console.log(array); – Rathish Kumar B Mar 22 '21 at 07:42
  • Return statement is misleading. Array is already modified. It can confuse that origin array will be untouched. – mikep Mar 23 '21 at 12:08
  • 55
    Year 2279. The mankind, after colonizing Mars, starts exploring new frontiers. But Javascript, still didn't get a .remove() function... – Bob Mar 25 '21 at 14:02
  • `Array.pull()` is what humankind needs the most. – a2br Apr 08 '21 at 16:03
  • 3
    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 Oh yeah, you're right! I didn't pick a correct name, I forgot `push`'s destructive behavior. I hate destructive methods when removing stuff. – a2br Apr 15 '21 at 12:22
1620

Edited on 2016 October

  • Do it simple, intuitive and explicit (Occam's razor)
  • Do it immutable (original array stay 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 using the filter polyfill from Mozilla.

Removing item (ECMA-262 Edition 5 code aka oldstyle 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 45 version, Firefox before 22 version, and Safari before 10 version. 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 47 version, Firefox before 43 version, Safari before 9 version, and Edge before 14 version so here is polyfill from Mozilla.

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

ashleedawg
  • 17,207
  • 5
  • 53
  • 80
ujeenator
  • 18,173
  • 2
  • 19
  • 27
1455

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
  • 7,179
  • 5
  • 9
  • 43
Peter Olson
  • 121,487
  • 47
  • 188
  • 235
532

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
  • 3,330
  • 1
  • 33
  • 53
xavierm02
  • 7,171
  • 1
  • 17
  • 24
  • 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
327

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
  • 105,049
  • 47
  • 242
  • 231
221

There are two major approaches:

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

  2. delete: delete anArray[index];

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
  • 3,178
  • 1
  • 20
  • 36
184
Array.prototype.remove_by_value = function(val) {
 for (var i = 0; i < this.length; i++) {
  if (this[i] === val) {
   this.splice(i, 1);
   i--;
  }
 }
 return this;
}[
 // call like
 (1, 2, 3, 4)
].remove_by_value(3);

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

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

rooms = rooms.remove_by_value('hello')

console.log(rooms)
Lioness100
  • 7,179
  • 5
  • 9
  • 43
Zirak
  • 35,198
  • 12
  • 75
  • 89
136

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

Find and move (move):

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

Use indexOf and splice (indexof):

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

Use only splice (splice):

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

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

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

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

Remove first occurrence:
    move_one 0.0041 ms
    indexof_one 0.0021 ms
slosd
  • 2,564
  • 2
  • 18
  • 17
105

This provides a predicate instead of a value.

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

Usage

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

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

Definition

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

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

 // Remove and return all occurrences

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

  for (var i = 0; i < array.length; ) {
   if (predicate(array[i])) {
    removed.push(array.splice(i, 1));
    continue;
   }
   i++;
  }
  return removed;
 },
};
amd
  • 18,048
  • 6
  • 45
  • 64
99

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
  • 358
  • 3
  • 13
Salvador Dali
  • 182,715
  • 129
  • 638
  • 708
93

John Resig posted a good implementation:

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

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

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

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

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

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

myArray.remove(8);

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

magiccrafter
  • 4,128
  • 1
  • 43
  • 38
Roger
  • 1,654
  • 17
  • 22
92

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
  • 1,629
  • 1
  • 14
  • 19
rajat44
  • 4,051
  • 5
  • 25
  • 34
  • 6
    This answer is nice because it creates a copy of the original array, instead of modifying the original directly. – Claudio Holanda Mar 16 '17 at 15:27
  • 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
91

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
  • 28,342
  • 21
  • 95
  • 123
vatsal
  • 3,387
  • 1
  • 17
  • 19
81

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
  • 28,342
  • 21
  • 95
  • 123
Loupax
  • 4,046
  • 4
  • 36
  • 63
77

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
  • 41,091
  • 27
  • 112
  • 129
Flavio Copes
  • 3,482
  • 3
  • 23
  • 29
71

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
  • 358
  • 3
  • 13
Ekramul Hoque
  • 4,441
  • 3
  • 28
  • 31
  • 4
    @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
61

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
  • 1,314
  • 1
  • 11
  • 25
Abdennour TOUMI
  • 64,884
  • 28
  • 201
  • 207
59

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,035
  • 20
  • 16
59

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
  • 2,396
  • 22
  • 28
  • 1
    This is the answer that worked for me when trying to update an array based on radio button toggling. – jdavid05 Apr 03 '19 at 11:52
  • 6
    Beware, if `"stringToRemoveFromArray"` is not located your in array, this will remove last element of array. – Fusion Apr 06 '19 at 23:35
51

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
  • 45
  • 6
Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
45

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
  • 28,342
  • 21
  • 95
  • 123
Alireza
  • 83,698
  • 19
  • 241
  • 152
40

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
  • 28,174
  • 7
  • 112
  • 121
sofiax
  • 429
  • 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
37

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;
});
Anik Islam Abhi
  • 24,324
  • 8
  • 52
  • 74
flurdy
  • 3,332
  • 26
  • 30
  • 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
36

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
AmerllicA
  • 15,720
  • 11
  • 72
  • 103
35

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
  • 933
  • 9
  • 19
35

ES10 Update

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.

Ammar
  • 45
  • 6
M. Twarog
  • 1,496
  • 3
  • 15
  • 34
31

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

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

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

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

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

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

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

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Adeel Imran
  • 8,751
  • 5
  • 45
  • 71
28

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

Live Demo

Edric
  • 18,215
  • 11
  • 68
  • 81
Jeff Noel
  • 6,972
  • 3
  • 35
  • 63
27

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
bjfletcher
  • 9,975
  • 3
  • 44
  • 64
  • 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
26

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
  • 2,860
  • 5
  • 32
  • 59
25
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
  • 28,342
  • 21
  • 95
  • 123
23

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,047
  • 9
  • 13
22

enter image description here

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

Above example uses array.prototype.filter function. It iterates over all array items, and returns only those satisfying arrow function. As a result, 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 how array.prototype.filter like this:

enter image description here

Considerations

Code quality

Array.filter.prototype 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 consider 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 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 (2.12.2020) 97,05% 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 really array you are processing has to be so big, it may be a sign that JavaScript should receive reduced array for processing from the data source.

Tomasz Smykowski
  • 24,175
  • 51
  • 149
  • 222
  • 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. – Daniel Foust Jan 13 '21 at 01:55
21

Immutable and one-liner way :

const newArr = targetArr.filter(e => e !== elementToDelete);
katma
  • 221
  • 1
  • 3
  • 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
20

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
  • 308
  • 2
  • 4
20

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,059
  • 3
  • 19
  • 37
Aram Grigoryan
  • 688
  • 1
  • 6
  • 23
18

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
  • 28,342
  • 21
  • 95
  • 123
nsantana
  • 1,692
  • 12
  • 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
17

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
  • 28,342
  • 21
  • 95
  • 123
Enrico
  • 533
  • 8
  • 26
17

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
  • 28,342
  • 21
  • 95
  • 123
NullPointer
  • 2,620
  • 3
  • 30
  • 56
15

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
  • 28,342
  • 21
  • 95
  • 123
codepleb
  • 8,529
  • 10
  • 50
  • 93
  • @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
14

There are many ways to remove a specific element from a Javascript array. Following are 05 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 utilizing above methods we utilized 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 05) is more appropriate for solving the above issue.

I wanted to make an answer with simple methods we can utilize to remove an element from the array. Your valuable feedback and comments are highly appreciated to improve my answer.

Pawara Siriwardhane
  • 909
  • 4
  • 11
  • 24
13

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
  • 28,342
  • 21
  • 95
  • 123
Redu
  • 19,106
  • 4
  • 44
  • 59
13

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
  • 1,715
  • 9
  • 11
  • 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
12

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

function destroy(arr, val) {
    for (var i = 0; i < arr.length; i++) if (arr[i] === val) arr.splice(i, 1);
    return arr;
}
yckart
  • 28,174
  • 7
  • 112
  • 121
12

In CoffeeScript:

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

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
  • 28,342
  • 21
  • 95
  • 123
alejandro
  • 2,608
  • 1
  • 15
  • 24
12

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
  • 10,479
  • 10
  • 80
  • 104
12
[2,3,5].filter(i => ![5].includes(i))
12

Immutable way of removing an element from array using 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]
Ahmad
  • 776
  • 1
  • 6
  • 14
  • 6
    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
  • Yes, you are right. This is an immutable way of removing an element. Thanks for clearing this out. – Ahmad Jul 07 '20 at 17:26
11

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
  • 28,342
  • 21
  • 95
  • 123
hailong
  • 927
  • 9
  • 17
11

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
  • 507
  • 3
  • 13
Ashish
  • 1,418
  • 12
  • 17
11

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
  • 28,342
  • 21
  • 95
  • 123
Taylor Hawkes
  • 401
  • 5
  • 7
10

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
  • 28,342
  • 21
  • 95
  • 123
Do Hoa Vinh
  • 312
  • 4
  • 11
10

Using 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)
10 Rep
  • 2,325
  • 7
  • 15
  • 28
shweta ghanate
  • 121
  • 1
  • 4
9

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,413
  • 2
  • 27
  • 32
9

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
  • 28,342
  • 21
  • 95
  • 123
mpen
  • 237,624
  • 230
  • 766
  • 1,119
  • `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
9

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
  • 358
  • 3
  • 13
Sujith S
  • 415
  • 5
  • 7
  • 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
9

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
  • 28,342
  • 21
  • 95
  • 123
Ravi Makwana
  • 1,864
  • 1
  • 20
  • 29
9

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,132
  • 1
  • 7
  • 19
8

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
  • 28,342
  • 21
  • 95
  • 123
Nejc Lepen
  • 317
  • 3
  • 4
  • 14
    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
8

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
  • 28,342
  • 21
  • 95
  • 123
Kamuran Sönecek
  • 3,088
  • 2
  • 24
  • 49
8

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
  • 28,342
  • 21
  • 95
  • 123
Shawn Deprey
  • 569
  • 8
  • 20
  • 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
8

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
  • 28,342
  • 21
  • 95
  • 123
Stelios Voskos
  • 506
  • 5
  • 14
8

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
  • 28,342
  • 21
  • 95
  • 123
Ali Akram
  • 2,966
  • 1
  • 18
  • 29
8

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
  • 671
  • 9
  • 10
8

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
  • 28,342
  • 21
  • 95
  • 123
Srikrushna
  • 2,652
  • 30
  • 37
8

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
  • 28,342
  • 21
  • 95
  • 123
8

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
  • 28,342
  • 21
  • 95
  • 123
pritam
  • 1,904
  • 1
  • 15
  • 24
  • 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. – die maus Mar 24 '21 at 15:38
8

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
  • 28,342
  • 21
  • 95
  • 123
Arun s
  • 507
  • 3
  • 13
8

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
  • 28,342
  • 21
  • 95
  • 123
ifelse.codes
  • 1,581
  • 16
  • 14
7

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
  • 28,342
  • 21
  • 95
  • 123
mboeckle
  • 868
  • 12
  • 25
  • Removes last item if searched item not found – Hontoni Apr 30 '14 at 17:05
  • 1
    yes correct, you should know which element you want to remove like in the other examples. – mboeckle May 01 '14 at 17:00
  • 4
    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
7

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
  • 28,342
  • 21
  • 95
  • 123
MEC
  • 1,322
  • 1
  • 15
  • 22
7

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
  • 28,342
  • 21
  • 95
  • 123
Mahendra Kulkarni
  • 1,199
  • 1
  • 18
  • 31
7

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
  • 289
  • 4
  • 6
7

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
  • 17,551
  • 4
  • 57
  • 56
7

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
  • 28,342
  • 21
  • 95
  • 123
Ajay Thakur
  • 1,018
  • 6
  • 19
6

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
  • 28,342
  • 21
  • 95
  • 123
Gaurang Patel
  • 379
  • 4
  • 10
6

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
  • 9,885
  • 2
  • 50
  • 68
6

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
  • 513
  • 5
  • 12
6

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
  • 167
  • 1
  • 4
6

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
  • 145
  • 1
  • 3
  • 10
6

splice() function is able to give you back item in array as well as remove item/ items from 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);
MSA
  • 101
  • 1
  • 9
6
  • 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
  • 616
  • 1
  • 8
  • 19
5
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
  • 694
  • 5
  • 11
5

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
  • 28,342
  • 21
  • 95
  • 123
rncrtr
  • 2,984
  • 2
  • 20
  • 31
5

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
  • 28,342
  • 21
  • 95
  • 123
Eugene Tiurin
  • 3,383
  • 3
  • 30
  • 32
5

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
  • 28,342
  • 21
  • 95
  • 123
hygull
  • 7,072
  • 2
  • 35
  • 42
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
  • 28,342
  • 21
  • 95
  • 123
Phil
  • 962
  • 1
  • 15
  • 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

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
  • 28,342
  • 21
  • 95
  • 123
Sebastien H.
  • 5,543
  • 2
  • 24
  • 32
5

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
  • 28,342
  • 21
  • 95
  • 123
Chang
  • 367
  • 1
  • 5
  • 15
5

I like this one-liner:

arr.includes(val) && arr.splice(arr.indexOf(val), 1)
  • ES6 (no IE 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)

oriadam
  • 5,404
  • 2
  • 35
  • 39
4

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
  • 28,342
  • 21
  • 95
  • 123
Matt Brock
  • 5,123
  • 1
  • 24
  • 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
4

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);
Giacomo Casadei
  • 533
  • 1
  • 2
  • 15
4

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, which makes sense given that it merely edits an existing array whereas filter creates a new one.

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.

Asker
  • 700
  • 1
  • 6
  • 21
3

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
  • 358
  • 3
  • 13
3

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
  • 840
  • 14
  • 30
Force Bolt
  • 273
  • 5
2
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,052
  • 2
  • 18
  • 35
2

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);
  • 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
2
var arr =[1,2,3,4,5];

arr.splice(0,1)

console.log(arr)

Output [2, 3, 4, 5];

Machavity
  • 28,730
  • 25
  • 78
  • 91
2

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

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

start

The index at which to start changing the array (with origin 0). If greater than the length of the array, the actual starting index will be set to the length of the array. If negative, it will begin that many elements from the end of the array (with origin -1) and will be set to 0 if the absolute value is greater than the length of the array.

deleteCount Optional

An integer indicating the number of old array elements to remove.

If deleteCount is omitted, or if its value is larger than array.length - start (that is, if it is greater than the number of elements left in the array, starting at start), then all of the elements from start through the end of the array will be deleted. If deleteCount is 0 or negative, no elements are removed. In this case, you should specify at least one new element (see below).

item1, item2, ... Optional

The elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array.

For more references, kindly go through:

Array.prototype.splice()

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Ashish
  • 1,418
  • 12
  • 17
2

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
  • 488
  • 5
  • 11
2

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
  • 28,342
  • 21
  • 95
  • 123
mekbib.awoke
  • 496
  • 1
  • 5
  • 12
  • 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
2

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
  • 53,729
  • 20
  • 259
  • 241
2

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
  • 30,672
  • 69
  • 32
  • 52
Masoud Aghaei
  • 358
  • 3
  • 13
1
    Array.prototype.remove = function(start, end) {
        var n = this.slice((end || start) + 1 || this.length);
        return this.length = start < 0 ? this.length + start : start,
        this.push.apply(this, n)
    }

start and end can be negative. In that case they count from the end of the array.

If only start is specified, only one element is removed.

The function returns the new array length.

z = [0,1,2,3,4,5,6,7,8,9];

newlength = z.remove(2,6);

(8) [0, 1, 7, 8, 9]

z=[0,1,2,3,4,5,6,7,8,9];

newlength = z.remove(-4,-2);

(7) [0, 1, 2, 3, 4, 5, 9]

z=[0,1,2,3,4,5,6,7,8,9];

newlength = z.remove(3,-2);

(4) [0, 1, 2, 9]

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Zibri
  • 7,056
  • 2
  • 42
  • 38
1

You can use filter for that

function removeNumber(arr, num){
    return arr.filter(el => {return el !== num});
 }

 let numbers = [1,2,3,4];
 numbers = removeNumber(numbers, 3);
 console.log(numbers); // [1,2,4]
Ran Turner
  • 1,710
  • 1
  • 6
  • 10
1

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
  • 228
  • 1
  • 8
  • 24
-2

You can use

Array.splice(index);
Dharman
  • 21,838
  • 18
  • 57
  • 107
  • 1
    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
-17
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
  • 19,015
  • 10
  • 59
  • 90