To resolve the issue, I added an unique ID to each element, like {A1;123,A2;432,A3;123,A4;543,A5;123,A6;123} and in this case finding a specific element is much easier with same function.
Remove a string from string array
-
23-03-2022 - |
سؤال
I am very beginner in JavaScript.
I have an string array like this : 123,432,123,543,123,123
I want to remove the 3dr number from this string.
I have found following function to remove a text value from an string array, but it's not working for arrays with duplicated values in them.
Array.prototype.removeByValue = function (val) {
for (var i = 0; i < this.length; i++) {
if (this[i] == val) {
this.splice(i, 1);
break;
}
}
}
Any suggestions to solve this issue is appreciated.
المحلول 3
نصائح أخرى
you can use filter:
var ary = ['three', 'seven', 'eleven'];
ary = ary.filter(function(v) {
return v !== 'seven';
});
and extend your array
Array.prototype.remove = function(value) {
return ary.filter(function(v) {
return v != value;
});
}
var ary = ['three', 'seven', 'eleven'];
ary = ary.remove('seven'),
console.log(ary)
Just keep going then:
Array.prototype.removeByValue = function (val) {
for (var i = 0; i < this.length; i++) {
if (this[i] == val) {
this.splice(i, 1);
i--; //Decrement after removing
//No break
}
}
}
The more idiomatic way is this.splice(i--, 1)
but this should be clearer in what order they happen.
var a = [1,2,1,1,2,2];
a.removeByValue(1);
a; //[2, 2, 2]
لا تنتمي إلى StackOverflow