ngmir
ngmir

Reputation: 488

JS: Remove Element from an Array based on RegExp

So I have a JavaScript array going somewhat like

My problem is the element "Stuff (5 of 5)". Basically, I dont want this to appear in the array. It wouldnt be a big problem if the was always the same, but the array is generated dynamically and the numbers behind differ. So, for example, on time it is "Stuff (2 of 3)", another time "Stuff (6 of 6)" and so on and so on. The first part stays the same.

So I thought Regular Expressions would solve the problem as thats what they actually are for. So I hacked together this code:

var regExpStuff = /Stuff\b/;
var array = removeItem(unique, regExpStuff);

The function removeItem() looks like this:

//remove item (string or number) from an array
    function removeItem(originalArray, itemToRemove) {
        var j = 0;
        while (j < originalArray.length) {
            if (originalArray[j] == itemToRemove) {
                originalArray.splice(j, 1);
        } else { j++; }
    }
    return originalArray;
    }

The function works fine with simple strings like "string", but it doesn't this way.
Any ideas what could be wrong? Help is highly appreciated,

Benny

Upvotes: 0

Views: 6834

Answers (2)

Martin
Martin

Reputation: 71

here is a graphical solution to the remove of the elements i like to see how things are changing

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
    var fruits= ["Banana", "Orange", "Lemon", "Apple", "Mango"];
    for (var i=0;i<fruits.length;i++){

    if( fruits[i] == "Lemon" ){ //remove Lemon
      var citrus = fruits.splice(i,1);
      i--;
    }
    if( fruits[i] == "Apple" ){ //remove Apple
      var citrus = fruits.splice(i,1);
      i--;
    }
    document.getElementById("demo").innerHTML = fruits+'<br>'+citrus;
 }
}
</script>
</body>
</html>

Upvotes: 1

SLaks
SLaks

Reputation: 887777

When you write if (originalArray[j] == itemToRemove), you are checking whether originalArray[j] is equal to the parameter. Since the string "# Stuff (5 of 5)" is not equal to your regex (after all, it's a string, not a regex), you're not removing anything.

You need to change the method to check the regex.
For example:

function removeMatching(originalArray, regex) {
    var j = 0;
    while (j < originalArray.length) {
        if (regex.test(originalArray[j]))
            originalArray.splice(j, 1);
        else
            j++;
    }
    return originalArray;
}

Upvotes: 3

Related Questions