1

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)
      }
   });
0

2 Answers 2

4

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));
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect i never even thought about joining it and THEN filtering it. Thanks
No worries @FernandoB, always glad to help. If my answer fixed your problem please accept it.
1

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);

1 Comment

Thank you! I've never heard or completely forgot about the some method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.