0

my problem might not be as challenging as some other similar questions but they were a little to much for me.

I have an array of objects that I need to filter by name against a string array of names, if the names match I want to remove the object with the name that matches

so like the following:

nameObjects = [{name: 'name3', value: 'some val'},{name: 'name1', value:'some other val'}]
names = ['name1','name2','name3']

I've tried the following just using for loops but I'm sure that there is a quicker (and correct lol) filter method that works

         for(i=0; i < this.names.length; i++){
            for(j=0; j < this.nameObjects.length; j++){

              if(this.names[i] === this.nameObjects[j].name){
                this.files.splice(i,this.nameObjects[j])
              }
            }
          }

also sorry for the poor logic ^

2 Answers 2

3

You should not mutate the array while you are looping over it.

You can simply use Array.prototype.filter with Array.prototype.includes to get the desired result

const nameObjects = [{name: 'name3', value: 'some val'},{name: 'name1', value:'some other val'}];
const names = ['name2','name3'];
const res = nameObjects.filter(obj => !names.includes(obj.name));
console.log(res);

Sign up to request clarification or add additional context in comments.

1 Comment

I see, so take the opposite, thank you this worked out perfectly for me!
1

const nameObjects = [
    { name: "name3", value: "some val" },
    { name: "name1", value: "some other val" },
];
const names = ["name1", "name2"];

const result = nameObjects.filter(obj => !names.includes(obj.name));

console.log(result);

Comments

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.