Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - filter an array of objects based on values in another array of objects

Tags:

angular

I have to filter an array of objects based on some preferences.

The Array I need to filter looks like this:

const products = [
    {value: 'v1', color: 'blue'},
    {value: 'v1', color: 'black'},
    {value: 'v1', color: 'red'},
    {value: 'v2', color: 'green'},
    {value: 'v2', color: 'red'},
    {value: 'v3', color: 'red'},
    {value: 'v4', color: 'blue'}
]

The preferences look like this:

const preferences = [
    {type: {value: 'v1', label: 'l1'}, color: 'blue'},
    {type: {value: 'v1', label: 'l1'}, color: 'red'},
    {type: {value: 'v2', label: 'l2'}, color: 'blue'},    
    {type: {value: 'v3', label: 'l3'}, color: 'red'},
    {type: {value: 'v4', label: 'l4'}, color: 'green'}
]

The filter should return all objects that match both value AND color of the preferences. So the desired result should be:

[
    {value: 'v1', color: 'blue'},
    {value: 'v1', color: 'red'},
    {value: 'v3', color: 'red'},
]

I have tried to use the following function from the example I found here:

function filterArray(allObjects, preferenceFilter) {
  const filterKeys = Object.keys(preferenceFilter);
  return allObjects.filter(item => {
    return filterKeys.every(key => {
      if (typeof preferenceFilter[key] !== 'function') return true;
      return preferenceFilter[key](item[key]);
    });
  });
}

The problem is that I need to convert the preferences into filter criteria of the form:

{color: x => x === 'red', type: y => y === 'v1' || y === 'v3'},
{color: x => x === 'blue', type: y => y === 'v1' || y === 'v2'},
{color: x => x === 'green', type: y => y === 'v4'}

How do I do this? Or is there a better way of solving this problem.

Thanks in advance for any help!

like image 606
Niels Ferguson Avatar asked Dec 18 '25 16:12

Niels Ferguson


1 Answers

Try this, I have tested it, as per your use case. It is working fine.

var final = [];
for(let i=0 ; i<products.length; i++){
    preferences.map((data)=>{
        if(data.color === products[i].color && data.type.value === products[i].value){
            final.push(data);
        }
    })

}
console.log(final)
like image 97
Mohit Pandey Avatar answered Dec 20 '25 07:12

Mohit Pandey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!