Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you can achive it using filter some and includes

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",
];

const arr3 = arr_2.filter(url => !arr_1.some(domain => url.includes(domain)))

console.log(arr3)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading