1

I have an array of objects like:

types: [
{
 id: 1,
 name: "Hello"
},
{
 id: 2,
 name: "World"
},
{
 id: 3,
 name: "Jon Doe"
}
]

And I also have a simple array like this:

selected_types = [1, 2]

The desired result should filter the "types" array and exclude all the ids that are present in the "selected_types" array, like below:

final_types: [
{
 id: 3,
 name: "Jon Doe"
}
]

I have absolutely no idea on how to achieve this, but below is my attempt:

 this.types.filter(obj => {
 for (let i = 0; i < this.selected_types.length; i++) {
 if (obj.id !== selected_types[i]) {
 final_types.push(attribute);
 }
 }
 });
asked Sep 26, 2019 at 8:57

3 Answers 3

3

Just use this.types.filter(({id}) => !this.selected_types.includes(id)):

let types = [{
 id: 1,
 name: "Hello"
 },
 {
 id: 2,
 name: "World"
 },
 {
 id: 3,
 name: "Jon Doe"
 }
]
let selected_types = [1, 2];
let resArr = types.filter(({id}) => !selected_types.includes(id));
console.log(resArr);

answered Sep 26, 2019 at 8:59
Sign up to request clarification or add additional context in comments.

1 Comment

Don't know if it would be clear for author. I would recommend to add that ({id}) is the same as let id = obj.id.
0

You can achieve Javascript's native method filter, which finally returns a new object

let types = [{
 id: 1,
 name: "Hello"
 },
 {
 id: 2,
 name: "World"
 },
 {
 id: 3,
 name: "Jon Doe"
 }
]
let selected_types = [1, 2];
types = types.filter(obj => {
 if (selected_types.indexOf(obj.id) === -1) {
 return obj
 }
});
answered Sep 26, 2019 at 9:37

Comments

0

Filtering the array types can get you what you want.

result = types.filter(el => !selected_types.includes(el.id))
answered Sep 12, 2023 at 20:55

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.