1

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.

2
  • Presumably you have an array like this: [123, 432, 123, 543, 123, 123]. You just want to remove the third element, no matter what it is? Commented Mar 14, 2013 at 13:26
  • @lonesomeday, it does matter. Commented Mar 14, 2013 at 13:37

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

But this is not in-place, any other references are still pointing to an array with "three seven eleven"
0

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]

Comments

-1

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.

2 Comments

if you do this, it is not a array, its a object!
its array, @silly!!! Does it matter what characters you have in your elements? @silly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.