javascriptarraysfilteringarray-splice

Filter an Array of strings using Filtered String and Remove from Original Array


I want to remove some elements from the array containing the word Evil (filterString).

let guests = ["Partner", "Evil Nice Relative 1", "Nice Relative 2", "Evil One", "another evil", "another one", "another evil is here", "strange Evil is here", "someone Nicer", "Ugly Evil Bad"];

const filteredArray = [];
const filterString = "Evil";

function checkEvil() {
    guests.filter((element, index) => {
        if (element.toLowerCase().indexOf(filterString.toLowerCase()) !== -1) {
            console.log(index);
            guests.splice(index,1);
        } else {
            filteredArray.push(element);
        }
    });
    console.log(guests);
}

Here is what I get for the original array (guests):


    ['Partner', 'Nice Relative 2', 'another evil', 'another one', 'strange Evil is here', 'someone Nicer']

Just want the guests array updated once the desired string (Evil) is filtered.


Solution

  • Since you want to mutate the original array then you can do as:

    let guests = [
      "Partner",
      "Evil Nice Relative 1",
      "Nice Relative 2",
      "Evil One",
      "another evil",
      "another one",
      "another evil is here",
      "strange Evil is here",
      "someone Nicer",
      "Ugly Evil Bad",
    ];
    
    const filterString = "Evil";
    
    function checkEvil() {
      for (let i = guests.length - 1; i >= 0; i--) {
        const element = guests[i];
        if (element.toLowerCase().indexOf(filterString.toLowerCase()) !== -1) {
          guests.splice(i, 1);
        }
      }
      console.log(guests);
    }
    
    checkEvil();


    1) You can easily achieve the result using filter and match as:

    const arr = [
      "Partner",
      "Nice Relative 2",
      "another evil",
      "another one",
      "strange Evil is here",
      "someone Nicer",
    ];
    const result = arr.filter((s) => !s.match(/evil/i));
    console.log(result);

    2) You can also do this using forEach and match as:

    let guests = [
      "Partner",
      "Evil Nice Relative 1",
      "Nice Relative 2",
      "Evil One",
      "another evil",
      "another one",
      "another evil is here",
      "strange Evil is here",
      "someone Nicer",
      "Ugly Evil Bad",
    ];
    
    const filteredArray = [];
    const filterString = "Evil";
    
    function checkEvil() {
      guests.forEach(element => {
        if (!element.match(/evil/i)) filteredArray.push(element);
      });
    }
    checkEvil();
    console.log(filteredArray);