Home > Enterprise >  I am looking for an efficient way to remove items from a JavaScript array if they are present in ano
I am looking for an efficient way to remove items from a JavaScript array if they are present in ano

Time:05-06

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

CodePudding user response:

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".

CodePudding user response:

Your code right now is returning the whole arr_2 because your filtering logic does not check if each item of arr_2 contains one of the matching strings in arr_1.

indexOf(arr_1) is essentially searching each item in arr_2 for the entire arr_1 array. The function will always return -1 because each item of arr_2 is a string and will never match with the entire arr_1 array.

I assume you'd want to go through each item in arr_1 as well, so you should probably do arr_1.forEach((item1) => { }) inside the forEach loop for arr_2, and do the indexOf check inside this inner loop.

CodePudding user response:

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)

CodePudding user response:

You need to change loop logic

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

console.log(filtered_arr)
  • Related