How to remove item from array by value?
JavascriptArraysJavascript Problem Overview
Is there a method to remove an item from a JavaScript array?
Given an array:
var ary = ['three', 'seven', 'eleven'];
I would like to do something like:
removeItem('seven', ary);
I've looked into splice()
but that only removes by the position number, whereas I need something to remove an item by its value.
Javascript Solutions
Solution 1 - Javascript
You can use the indexOf
method like this:
var index = array.indexOf(item);
if (index !== -1) {
array.splice(index, 1);
}
>Note: You'll need to shim it for IE8 and below
var array = [1,2,3,4]
var item = 3
var index = array.indexOf(item);
array.splice(index, 1);
console.log(array)
Solution 2 - Javascript
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).
Solution 3 - Javascript
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;
};
}
Solution 4 - Javascript
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.
Solution 5 - Javascript
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')
Solution 6 - Javascript
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');
Solution 7 - Javascript
The simplest solution is:
array - array for remove some element valueForRemove; valueForRemove - element for remove;
array.filter(arrayItem => !array.includes(valueForRemove));
More simple:
array.filter(arrayItem => arrayItem !== valueForRemove);
No pretty, but works:
array.filter(arrayItem => array.indexOf(arrayItem) != array.indexOf(valueForRemove))
No pretty, but works:
while(array.indexOf(valueForRemove) !== -1) {
array.splice(array.indexOf(valueForRemove), 1)
}
P.S. The filter() method creates a new array with all elements that pass the test implemented by the provided function. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Solution 8 - Javascript
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');
Solution 9 - Javascript
Simply
var ary = ['three', 'seven', 'eleven'];
var index = ary.indexOf('seven'); // get index if value found otherwise -1
if (index > -1) { //if found
ary.splice(index, 1);
}
Solution 10 - Javascript
Here's a version that uses jQuery's inArray function:
var index = $.inArray(item, array);
if (index != -1) {
array.splice(index, 1);
}
Solution 11 - Javascript
var index = array.indexOf('item');
if(index!=-1){
array.splice(index, 1);
}
Solution 12 - Javascript
What you're after is filter
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
This will allow you to do the following:
var ary = ['three', 'seven', 'eleven'];
var aryWithoutSeven = ary.filter(function(value) { return value != 'seven' });
console.log(aryWithoutSeven); // returns ['three', 'eleven']
This was also noted in this thread somewhere else: https://stackoverflow.com/a/20827100/293492
Solution 13 - Javascript
ES6 way.
const commentsWithoutDeletedArray = commentsArray.filter(comment => comment.Id !== commentId);
Solution 14 - Javascript
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']
Solution 15 - Javascript
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]
Solution 16 - Javascript
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' });
Solution 17 - Javascript
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')
Solution 18 - Javascript
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.
Solution 19 - Javascript
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]
Solution 20 - Javascript
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;
}
Solution 21 - Javascript
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.
Solution 22 - Javascript
You can achieve this using Lodash _.remove
function.
var array = ['three', 'seven', 'eleven'];
var evens = _.remove(array, function(e) {
return e !== 'seven';
});
console.log(evens);
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
Solution 23 - Javascript
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"]
Solution 24 - Javascript
You can use without
or pull
from Lodash:
const _ = require('lodash');
_.without([1, 2, 3, 2], 2); // -> [1, 3]
Solution 25 - Javascript
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;
}
Solution 26 - Javascript
var remove = function(array, value) {
var index = null;
while ((index = array.indexOf(value)) !== -1)
array.splice(index, 1);
return array;
};
Solution 27 - Javascript
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' ]
Solution 28 - Javascript
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)
Solution 29 - Javascript
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]
Solution 30 - Javascript
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
Solution 31 - Javascript
I tried using the function method from jbaron above but found that I needed to keep the original array intact for use later, and creating a new array like this:
var newArray = referenceArray;
apparently creates by reference instead of value because when I removed an element from newArray the referenceArray also had it removed. So I decided to create a new array each time like this:
function newArrRemoveItem(array, item, newArray){
for(var i = 0; i < array.length; i++) {
if(array[i]!=item){
newArray.push(array[i]);
}
}
}
Then I use it like this in another function:
var vesselID = record.get('VesselID');
var otherVessels = new Array();
newArrRemoveItem(vesselArr,vesselID,otherVessels);
Now the vesselArr remains intact while each time I execute the above code the otherVessels array includes all but the latest vesselID element.
Solution 32 - Javascript
//This function allows remove even array from array
var removeFromArr = function(arr, elem) {
var i, len = arr.length, new_arr = [],
sort_fn = function (a, b) { return a - b; };
for (i = 0; i < len; i += 1) {
if (typeof elem === 'object' && typeof arr[i] === 'object') {
if (arr[i].toString() === elem.toString()) {
continue;
} else {
if (arr[i].sort(sort_fn).toString() === elem.sort(sort_fn).toString()) {
continue;
}
}
}
if (arr[i] !== elem) {
new_arr.push(arr[i]);
}
}
return new_arr;
}
Example of using
var arr = [1, '2', [1 , 1] , 'abc', 1, '1', 1];
removeFromArr(arr, 1);
//["2", [1, 1], "abc", "1"]
var arr = [[1, 2] , 2, 'a', [2, 1], [1, 1, 2]];
removeFromArr(arr, [1,2]);
//[2, "a", [1, 1, 2]]
Solution 33 - Javascript
Another variation:
if (!Array.prototype.removeArr) {
Array.prototype.removeArr = function(arr) {
if(!Array.isArray(arr)) arr=[arr];//let's be nice to people who put a non-array value here.. that could be me!
var that = this;
if(arr.length){
var i=0;
while(i<that.length){
if(arr.indexOf(that[i])>-1){
that.splice(i,1);
}else i++;
}
}
return that;
}
}
It's indexOf() inside a loop again, but on the assumption that the array to remove is small relative to the array to be cleaned; every removal shortens the while loop.
Solution 34 - Javascript
Check out this way:
delete this.arrayName[this.arrayName.indexOf(value)];
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete
Solution 35 - Javascript
CoffeeScript+jQuery variant:
arrayRemoveItemByValue = (arr,value) ->
r=$.inArray(value, arr)
unless r==-1
arr.splice(r,1)
# return
arr
console.log arrayRemoveItemByValue(['2','1','3'],'3')
it remove only one, not all.
Solution 36 - Javascript
//edited thanks to MarcoCI for the advice
try this:
function wantDelete(item, arr){
for (var i=0;i<arr.length;i++){
if (arr[i]==item){
arr.splice(i,1); //this delete from the "i" index in the array to the "1" length
break;
}
}
}
var goodGuys=wantDelete('bush', ['obama', 'bush', 'clinton']); //['obama', 'clinton']
hope this help you
Solution 37 - Javascript
You can use lodash pull function
var ary = ['three', 'seven', 'eleven'];
_.pull(ary, 'seven'); // ['three', 'eleven']
console.log(ary)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.6.1/lodash.js"></script>