Search code examples
javascriptarraysindexof

I am looking for an efficient way to remove items from a JavaScript array if they are present in another array. Using indexOf


I want to remove those items from arr_2 which contains the domain name from arr_1

let arr_1 = ["domain1.com", "domain2.com"];

let arr_2 = [
  "domain1.com/about-us",
  "domain3.com/contact-us",
  "domain4.com/privacy-policy",
  "domain2.com/pricing-plans",
  "sub.domain2.com/home-1",
];

let filtered_arr = [];

arr_2.forEach((item) => {
  if (item.indexOf(arr_1) == -1) {
    filtered_arr.push(item);
  }
});

console.log(filtered_arr);

i want the result ["domain3.com/contact-us", "domain4.com/privacy-policy"] from this code, but it prints the whole arr_2


Solution

  • You can't call indexOf on a string and pass an array as an argument.
    You should use find to check if item has a domain from arr_1.
    And it's a lot cleaner code using filter than forEach.

    let arr_1 = ["domain1.com", "domain2.com"];
    
    let arr_2 = [
      "domain1.com/about-us",
      "domain3.com/contact-us",
      "domain4.com/privacy-policy",
      "domain2.com/pricing-plans",
      "sub.domain2.com/home-1",
    ];
    
    let filtered_arr = arr_2.filter(item => {
      return !arr_1.find(domain => item.includes(domain));
    });
    
    console.log(filtered_arr);

    Note: This would also filter out "example.com/domain1.com".