My situation:
var id_tag = [1,2,3,78,5,6,7,8,47,34,90];
I would like to delete where id_tag = 90
and to return:
var id_tag = [1,2,3,78,5,6,7,8,47,34];
How can I do that?
This question is related to
javascript
arrays
I like to use filter:
var id_tag = [1,2,3,78,5,6,7,8,47,34,90];
// delete where id_tag = 90
id_tag = id_tag.filter(function(x) {
if (x !== 90) {
return x;
}
});
var id_tag = [1,2,3,78,5,6,7,8,47,34,90];
var delete_where_id_tag = 90
id_tag =id_tag.filter((x)=> x!=delete_where_id_tag);
You can use lodash.js
_.pull(arrayName,valueToBeRemove);
In your case :- _.pull(id_tag,90);
As a variant
delete array[array.indexOf(item)];
If you know nothing about delete
operator, DON'T use this.
You'll want to use .indexOf()
and .splice()
. Something like:
tag_story.splice(tag_story.indexOf(90),1);
tag_story.splice(tag_story.indexOf(id_tag), 1);
Here are some helper functions I use:
Array.contains = function (arr, key) {
for (var i = arr.length; i--;) {
if (arr[i] === key) return true;
}
return false;
};
Array.add = function (arr, key, value) {
for (var i = arr.length; i--;) {
if (arr[i] === key) return arr[key] = value;
}
this.push(key);
};
Array.remove = function (arr, key) {
for (var i = arr.length; i--;) {
if (arr[i] === key) return arr.splice(i, 1);
}
};
If you're going to be using this often (and on multiple arrays), extend the Array object to create an unset function.
Array.prototype.unset = function(value) {
if(this.indexOf(value) != -1) { // Make sure the value exists
this.splice(this.indexOf(value), 1);
}
}
tag_story.unset(56)
function removeValue(arr, value) {
for(var i = 0; i < arr.length; i++) {
if(arr[i] === value) {
arr.splice(i, 1);
break;
}
}
return arr;
}
This can be called like so:
removeValue(tag_story, 90);
Source: Stackoverflow.com