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);
}
}
});
3 Answers 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
Ankit Agarwal
30.8k5 gold badges41 silver badges63 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Daniyal Lukmanov
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.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
Thirupathi Govindharaj
621 silver badge7 bronze badges
Comments
Filtering the array types can get you what you want.
result = types.filter(el => !selected_types.includes(el.id))
Comments
Explore related questions
See similar questions with these tags.
lang-js