A one-liner will do it,
var arr = ['three', 'seven', 'eleven'];
// Remove item 'seven' from array
var filteredArray = arr.filter[function[e] { return e !== 'seven' }]
//=> ["three", "eleven"]
// In ECMA6 [arrow function syntax]:
var filteredArray = arr.filter[e => e !== 'seven']
This makes use of the filter function in JS. It's supported in IE9 and up.
What it does [from the doc link]
filter[] calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array.
So basically, this is the same as all the other for [var key in ary] { ... }
solutions, except that the for in
construct is supported as of IE6.
Basically,
filter is a convenience method that looks a lot nicer [and is chainable] as opposed to the for in
construct [AFAIK].
TuralAsgar
1,0772 gold badges11 silver badges24 bronze badges
answered Dec 29, 2013 at 16:05
C BC B
11.4k4 gold badges35 silver badges47 bronze badges
8
This can be a global function or a method of a custom object, if you aren't allowed to add to native prototypes. It removes all of the items from the array that match any of the arguments.
Array.prototype.remove = function[] {
var what, a = arguments, L = a.length, ax;
while [L && this.length] {
what = a[--L];
while [[ax = this.indexOf[what]] !== -1] {
this.splice[ax, 1];
}
}
return this;
};
var ary = ['three', 'seven', 'eleven'];
ary.remove['seven'];
/* returned value: [Array]
three,eleven
*/
To make it a global-
function removeA[arr] {
var what, a = arguments, L = a.length, ax;
while [L > 1 && arr.length] {
what = a[--L];
while [[ax= arr.indexOf[what]] !== -1] {
arr.splice[ax, 1];
}
}
return arr;
}
var ary = ['three', 'seven', 'eleven'];
removeA[ary, 'seven'];
/* returned value: [Array]
three,eleven
*/
And to take care of IE8 and below-
if[!Array.prototype.indexOf] {
Array.prototype.indexOf = function[what, i] {
i = i || 0;
var L = this.length;
while [i < L] {
if[this[i] === what] return i;
++i;
}
return -1;
};
}
answered Oct 17, 2010 at 20:16
kennebeckennebec
100k31 gold badges104 silver badges126 bronze badges
19
You can use underscore.js. It really makes things simple.
For example, with this:
var result = _.without[['three','seven','eleven'], 'seven'];
And result
will be ['three','eleven']
.
In your case the code that you will have to write is:
ary = _.without[ary, 'seven']
It reduces the code that you write.
answered Feb 19, 2013 at 9:52
vatsalvatsal
3,7252 gold badges18 silver badges19 bronze badges
4
You can do it with these two ways:
const arr = ['1', '2', '3', '4'] // we wanna delete number "3"
The first way:
arr.indexOf['3'] !== -1 && arr.splice[arr.indexOf['3'], 1]
The second way [ES6] specially without mutate:
const newArr = arr.filter[e => e !== '3']
answered Dec 26, 2017 at 15:40
AmerllicAAmerllicA
24.9k12 gold badges118 silver badges143 bronze badges
0
Check out this way:
for[var i in array]{
if[array[i]=='seven']{
array.splice[i,1];
break;
}
}
and in a function:
function removeItem[array, item]{
for[var i in array]{
if[array[i]==item]{
array.splice[i,1];
break;
}
}
}
removeItem[array, 'seven'];
answered Jul 17, 2011 at 17:31
gadlolgadlol
1,2432 gold badges14 silver badges23 bronze badges
3
The simplest solution is:
array - array for remove some element valueForRemove; valueForRemove - element for remove;
array.filter[arrayItem => !array.includes[valueForRemove]];
More simple:
array.filter[arrayItem => arrayItem !== valueForRemove];
No pretty, but works:
array.filter[arrayItem => array.indexOf[arrayItem] != array.indexOf[valueForRemove]]
No pretty, but works:
while[array.indexOf[valueForRemove] !== -1] {
array.splice[array.indexOf[valueForRemove], 1]
}
P.S. The filter[] method creates a new array with all elements that pass the test implemented by the provided function. See //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
answered Feb 26, 2019 at 20:45
JackkobecJackkobec
5,11330 silver badges30 bronze badges
5
You can create your own method, passing throught the array and the value you want removed:
function removeItem[arr, item]{
return arr.filter[f => f !== item]
}
Then you can call this with:
ary = removeItem[ary, 'seven'];
answered May 10, 2020 at 18:03
ChiaroChiaro
1,36911 silver badges12 bronze badges
Method 1
var ary = ['three', 'seven', 'eleven'];
var index = ary.indexOf['seven']; // get index if value found otherwise -1
if [index > -1] { //if found
ary.splice[index, 1];
}
Method 2
One liner Solution
var ary = ['three', 'seven', 'eleven'];
filteredArr = ary.filter[function[v] { return v !== 'seven' }]
// Or using ECMA6:
filteredArr = ary.filter[v => v !== 'seven']
answered Oct 29, 2018 at 16:15
Dev MateeDev Matee
4,5162 gold badges28 silver badges31 bronze badges
2
Here's a version that uses jQuery's inArray function:
var index = $.inArray[item, array];
if [index != -1] {
array.splice[index, 1];
}
answered Jul 12, 2013 at 9:02
CorayThanCorayThan
16.4k27 gold badges109 silver badges154 bronze badges
2
var index = array.indexOf['item'];
if[index!=-1]{
array.splice[index, 1];
}
answered Nov 13, 2012 at 13:49
KldKld
6,7853 gold badges35 silver badges49 bronze badges
ES6 way.
const commentsWithoutDeletedArray = commentsArray.filter[comment => comment.Id !== commentId];
answered May 29, 2017 at 14:34
Oliver DixonOliver Dixon
6,6135 gold badges55 silver badges87 bronze badges
4
If you have unique values and ordering doesn't matter, use Set, it has delete[]:
var mySet = new Set[['three', 'seven', 'eleven']];
mySet.delete['seven']; // Returns true, successfully removed
[...mySet]; // Returns ['three', 'eleven']
answered May 18, 2017 at 14:05
greenegreene
5995 silver badges6 bronze badges
Really, i can't see why this can't be solved with
arr = arr.filter[value => value !== 'seven'];
Or maybe you want to use vanilla JS
arr = arr.filter[function[value] { return value !== 'seven' }];
answered Jul 13, 2018 at 1:18
rbenvenutorbenvenuto
2,4152 gold badges11 silver badges19 bronze badges
3
When you need to remove a value present multiple times in the array[e.g. [1,2,2,2, 4, 5,6]].
function removeFrmArr[array, element] {
return array.filter[e => e !== element];
};
var exampleArray = [1,2,3,4,5];
removeFrmArr[exampleArray, 3];
// return value like this
//[1, 2, 4, 5]
You can use splice to remove a single element from the array but splice can't remove multiple similar elements from the array.
function singleArrayRemove[array, value]{
var index = array.indexOf[value];
if [index > -1] array.splice[index, 1];
return array;
}
var exampleArray = [1,2,3,4,5,5];
singleArrayRemove[exampleArray, 5];
// return value like this
//[1, 2, 3, 4, 5]
Olcay Ertaş
5,7658 gold badges77 silver badges105 bronze badges
answered Feb 13, 2018 at 7:27
2
Seeing as there isn't a pretty one, here's a simple and reusable ES6 function.
const removeArrayItem = [arr, itemToRemove] => {
return arr.filter[item => item !== itemToRemove]
}
Usage:
const items = ['orange', 'purple', 'orange', 'brown', 'red', 'orange']
removeArrayItem[items, 'orange']
answered Jun 26, 2017 at 11:44
ShakespeareShakespeare
1,2869 silver badges15 bronze badges
3
Removing all matching elements from the array [rather than just the first as seems to be the most common answer here]:
while [$.inArray[item, array] > -1] {
array.splice[ $.inArray[item, array], 1 ];
}
I used jQuery for the heavy lifting, but you get the idea if you want to go native.
answered Jan 22, 2014 at 17:04
JasonJason
2,1912 gold badges22 silver badges22 bronze badges
1
In all values unique, you can:
a = new Set[[1,2,3,4,5]] // a = Set[5] {1, 2, 3, 4, 5}
a.delete[3] // a = Set[5] {1, 2, 4, 5}
[...a] // [1, 2, 4, 5]
answered Nov 23, 2018 at 10:58
a very clean solution working in all browsers and without any framework is to asign a new Array and simply return it without the item you want to delete:
/**
* @param {Array} array the original array with all items
* @param {any} item the time you want to remove
* @returns {Array} a new Array without the item
*/
var removeItemFromArray = function[array, item]{
/* assign a empty array */
var tmp = [];
/* loop over all array items */
for[var index in array]{
if[array[index] !== item]{
/* push to temporary array if not like item */
tmp.push[array[index]];
}
}
/* return the temporary array */
return tmp;
}
dcordz
1302 silver badges8 bronze badges
answered Jan 7, 2016 at 13:52
mtizzianimtizziani
83810 silver badges22 bronze badges
1
indexOf
is an option, but
it's implementation is basically searching the entire array for the value, so execution time grows with array size. [so it is in every browser I guess, I only checked Firefox].
I haven't got an IE6 around to check, but I'd call it a safe bet that you can check at least a million array items per second this way on almost any client machine. If [array size]*[searches per second] may grow bigger than a million you should consider a different implementation.
Basically you can use an object to make an index for your array, like so:
var index={'three':0, 'seven':1, 'eleven':2};
Any sane JavaScript environment will create a searchable index for such objects so that you can quickly translate a key into a value, no matter how many properties the object has.
This is just the basic method, depending on your need you may combine several objects and/or arrays to make the same data quickly searchable for different properties. If you specify your exact needs I can suggest a more specific data structure.
answered Oct 17, 2010 at 18:32
aaaaaaaaaaaaaaaaaaaaaaaa
3,5781 gold badge23 silver badges23 bronze badges
1
You can achieve this using Lodash _.remove
function.
var array = ['three', 'seven', 'eleven'];
var evens = _.remove[array, function[e] {
return e !== 'seven';
}];
console.log[evens];
answered Sep 3, 2018 at 9:11
Penny LiuPenny Liu
12.8k5 gold badges70 silver badges86 bronze badges
You can use without
or pull
from Lodash:
const _ = require['lodash'];
_.without[[1, 2, 3, 2], 2]; // -> [1, 3]
answered Jan 12, 2016 at 22:39
sakoviassakovias
1,2961 gold badge17 silver badges25 bronze badges
The trick is to go through the array from end to beginning, so you don't mess up the indices while removing elements.
var deleteMe = function[ arr, me ]{
var i = arr.length;
while[ i-- ] if[arr[i] === me ] arr.splice[i,1];
}
var arr = ["orange","red","black", "orange", "white" , "orange" ];
deleteMe[ arr , "orange"];
arr is now ["red", "black", "white"]
answered Mar 17, 2015 at 17:43
Non-destructive removal:
function removeArrayValue[array, value]
{
var thisArray = array.slice[0]; // copy the array so method is non-destructive
var idx = thisArray.indexOf[value]; // initialise idx
while[idx != -1]
{
thisArray.splice[idx, 1]; // chop out element at idx
idx = thisArray.indexOf[value]; // look for next ocurrence of 'value'
}
return thisArray;
}
answered Jun 25, 2016 at 12:17
var remove = function[array, value] {
var index = null;
while [[index = array.indexOf[value]] !== -1]
array.splice[index, 1];
return array;
};
answered Jan 13, 2013 at 21:51
1
Please do not use the variant with delete
- it makes a hole in the array as it does not re-index the elements after the deleted item.
> Array.prototype.remove=function[v]{
... delete this[this.indexOf[v]]
... };
[Function]
> var myarray=["3","24","55","2"];
undefined
> myarray.remove["55"];
undefined
> myarray
[ '3', '24', , '2' ]
mmohab
2,2134 gold badges27 silver badges42 bronze badges
answered May 5, 2014 at 16:10
Ilya SherIlya Sher
6015 silver badges4 bronze badges
I used the most voted option and created a function that would clean one array of words using another array of unwanted words:
function cleanArrayOfSpecificTerms[array,unwantedTermsArray] {
$.each[unwantedTermsArray, function[ index, value ] {
var index = array.indexOf[value];
if [index > -1] {
array.splice[index, 1];
}
}];
return array;
}
To use, do the following:
var notInclude = ['Not','No','First','Last','Prior','Next', 'dogs','cats'];
var splitTerms = ["call", "log", "dogs", "cats", "topic", "change", "pricing"];
cleanArrayOfSpecificTerms[splitTerms,notInclude]
answered Feb 10, 2015 at 16:06
maudulusmaudulus
9,9599 gold badges73 silver badges110 bronze badges
let arr = [5, 15, 25, 30, 35];
console.log[arr]; //result [5, 15, 25, 30, 35]
let index = arr.indexOf[30];
if [index > -1] {
arr.splice[index, 1];
}
console.log[arr]; //result [5, 15, 25, 35]
answered Apr 18, 2018 at 9:02
Asif voraAsif vora
2,6723 gold badges12 silver badges28 bronze badges
0
In a global function we can't pass a custom value directly but there are many way as below
var ary = ['three', 'seven', 'eleven'];
var index = ary.indexOf[item];//item: the value which you want to remove
//Method 1
ary.splice[index,1];
//Method 2
delete ary[index]; //in this method the deleted element will be undefined
answered Jun 28, 2018 at 18:11
SrikrushnaSrikrushna
3,7651 gold badge36 silver badges45 bronze badges
1