Home > Software engineering >  Filtering an object in an array requiring 2 criteria
Filtering an object in an array requiring 2 criteria

Time:09-29

What would be the best way of filtering out an object in an array based on 2 factors, I thought a simple && operator would work but I was mistaken.

{
  email: '[email protected]',
  accounts: [
    { name: 'Bob', country: 'UK' },
    { name: 'Chris', country: 'USA' },
    { name: 'Bob', country: 'USA' },
  ]
}

My original filter would just filter out based on accounts.name != 'Bob' however this can be problematic as there could be 2 Bobs with different countries.

let filterOut = result.accounts.filter(function (element) {
    return element.name != 'Bob' && element.country != 'UK';
});

How could I use filter (if that is even the best option here) to achive the below output:

[
    { name: 'Chris', country: 'USA' },
    { name: 'Bob', country: 'USA' },
]

CodePudding user response:

You could use an OR (||) to filter

data.accounts.filter(f => f.name != "Bob" || f.country == 'USA');

let data = {
  email: '[email protected]',
  accounts: [
    { name: 'Bob', country: 'UK' },
    { name: 'Chris', country: 'USA' },
    { name: 'Bob', country: 'USA' },
  ]
}

let filtered = data.accounts.filter(f => f.name != "Bob" || f.country == 'USA');

console.log(filtered)

CodePudding user response:

You are filtering out every value that is both not 'Bob' and not 'UK'.

Here are two possible solutions. The right answer probably depends on exactly what it means to filter "based on 2 factors".

const input = {
  email: '[email protected]',
  accounts: [
    { name: 'Bob', country: 'UK' },
    { name: 'Chris', country: 'USA' },
    { name: 'Bob', country: 'USA' },
  ],
};

// Filter out every value with either name 'Bob' or country 'UK'.
const outputV1 = input.accounts.filter(v => v.name !== 'Bob' || v.country !== 'UK');
console.log(outputV1);

// Filter out every value with name 'Bob' and country 'UK'.
const outputV2 = input.accounts.filter(v => `${v.name}-${v.country}` !== 'Bob-UK');
console.log(outputV2);

  • Related