开发者

JS: Remove Element from an Array based on RegExp

开发者 https://www.devze.com 2023-01-15 08:23 出处:网络
So I have a 开发者_JAVA技巧JavaScript array going somewhat like screw cap bottle [tech.] nonreturnable bottlemagnumempty

So I have a 开发者_JAVA技巧JavaScript array going somewhat like

  • screw cap bottle [tech.]
  • nonreturnable bottle magnum empty
  • tank
  • diving magnetic bottle [tech.]
  • unbreakable bottle
  • full
  • tank
  • diving
  • Stuff (5 of 5)
  • eine Flasche austrinken ein Baby mit
  • der Flasche ernähren ein Baby mit
  • der Flasche füttern mit der Flasche
  • aufziehen

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


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;
}


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号