Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

66
Views
Filtering an object in an array requiring 2 criteria

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@email.com',
  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' },
]
almost 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You could use an OR (||) to filter

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

let data = {
  email: 'email@email.com',
  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)

almost 4 years ago · Santiago Trujillo Report

0

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@email.com',
  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);

almost 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!