0

I have an array of objects stored in 'component' variable

component=[{id:1,type:Comp1},{id:2,type:Comp2},{id:3,type:Comp3},{id:4,type:Comp4},{id:5,type:Comp5}]

I want to filter it by type 'Comp1' and 'Comp2'. I tried the following code

this.filterComponent=[{id:1,type:Comp1},{id:2,type:Comp2}];
for(let i=0;i<this.filterComponent.length;i++)
 this.component=  this.component.filter(ob => ob.type == this.filterComponenet[i].type)

But it works only for a single value(if filteredComponent contains only one object). For instance,

this.filterComponent=[{id:1,type:Comp1}]

How to make it work for multiple values. Thanks in advance.

2 Answers 2

1

You're swallowing the previous filter's result, you should keep track, for example with the function concat or even with an additional array.

You can also use the function filter as follow:

this.filterComponent = [{id:1,type:Comp1},{id:2,type:Comp2}];
this.component = this.component.filter(({type}) => this.filterComponenet.some(({type: t}) => t === type));
Sign up to request clarification or add additional context in comments.

Comments

0

Maybe this?

var component=[{id:1,type:'Comp1'},{id:2,type:'Comp2'},{id:3,type:'Comp3'},{id:4,type:'Comp4'},{id:5,type:'Comp5'}];

var out = [];

for(i=0; i < component.length; i++){
	if(component[i].type == 'Comp1' || component[i].type == 'Comp2'){
		out.push(component[i]);
	}
}

console.log(out);

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.