Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

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.

share|improve this question
    
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? – lonesomeday Mar 14 '13 at 13:26
    
@lonesomeday, it does matter. – amir moradifard Mar 14 '13 at 13:37

3 Answers 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)
share|improve this answer
    
But this is not in-place, any other references are still pointing to an array with "three seven eleven" – Esailija Mar 14 '13 at 13:35
    
correct.... .... – silly Mar 14 '13 at 13:36
    
Thanks, this worked with me with some modifications! – amir moradifard Mar 14 '13 at 13:45

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]
share|improve this answer
up vote -1 down vote accepted

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.

share|improve this answer
    
if you do this, it is not a array, its a object! – silly Mar 18 '13 at 6:58
    
its array, @silly!!! Does it matter what characters you have in your elements? @silly – amir moradifard Mar 24 '13 at 13:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.