Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

63
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda