سؤال

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

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.

نصائح أخرى

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]
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top