Fernando B
Fernando B

Reputation: 891

How to remove object from array depending on child condition JS

I'm trying to remove/ or splice objects from an array on the condition of a property. if the property string includes a string then remove that object from the array. So filter an object based on its property looping through an array of string.

I have a object like so

let obj = [
    {
        "name": "product one"
    },
    {
        "name": "product two"
    },
    {
        "name": "item one"
    },
    {
        "name": "item three"
    }
]    

an array

let arr = ['one', 'item'] 

So i would like my final or return object to look like

[
  {
    name: "product two"
  }
]

I've tried for loops, double for loops, filters, and include and all fail. One thing to note is my json file that i'm importing has over 20,000 records, so idk if thats a reason it might be failing.

 var intersection = obj.filter(function (e) {
      for (const word of arr) {
         return !e.name.includes(word)
      }
   });

Upvotes: 1

Views: 282

Answers (2)

Jack Bashford
Jack Bashford

Reputation: 44135

To find the item which is not included in the array, use some on arr and invert the returned Boolean:

const intersection = obj.filter(({ name }) => !arr.some(e => name.includes(e)));

If there are a lot of records, then the above approach might be too slow - this approach is more efficient:

const re = new RegExp(arr.join("|"));
const intersection = obj.filter(({ name }) => !re.test(name));

Upvotes: 4

Titus
Titus

Reputation: 22484

The problem is that your loop returns after the first iteration which means that you're only checking if the element's name value matches the first element in the arr array.

Instead of a loop you can use .some(), here is an example:

let obj = [{
    "name": "product one"
  },
  {
    "name": "product two"
  },
  {
    "name": "item one"
  },
  {
    "name": "item three"
  }
]

let arr = ['one', 'item']

const intersection = obj.filter(({
  name
}) => !arr.some(v => name.includes(v)));
console.log(intersection);

Upvotes: 1

Related Questions