Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

119
Visualizações
filter array based on another nested array

In the code below, I apply filter on array based on other arrays. For example : Filter data array based on property names from cols and values from values array.

const
    data = [{ name: "Tiger Nixon", position: "Accountant", salary: 10800, start_date: "2011\\/04\\/25", office: "Edinburgh", rating: 5421 }, { name: "Garrett Winters", position: "Accountant", salary: 170750, start_date: "2011\\/07\\/25", office: "Tokyo", rating: 8422 }, { name: "Garrett Winters", position: "Analyst", salary: 170750, start_date: "2011\\/07\\/25", office: "Tokyo", rating: 8422 }, { name: "Ashton Cox", position: "Junior Technical Author", salary: 86000, start_date: "2009\\/01\\/12", office: "San Francisco", rating: 1562 }, { name: "Cedric Kelly", position: "Senior Javascript Developer", salary: 433060, start_date: "2012\\/03\\/29", office: "Edinburgh", rating: 6224 }],
    cols = ['name', 'position'],
    values = ['Garrett Winters', 'Accountant'],
    result = data.filter(o => cols.every((k, i) => o[k] === values[i]));
    
    console.log(result);

The above code is working fine. But if I have nested array for numeric in values (see below). I want to accommodate this condition salary >= nestedarray[0] && salary <= nestedarray[1]

cols = ['salary', 'position']
values = [[50000,500000], 'Accountant']

I tried this but not working -

result = data.filter(o => cols.every((k, i) => if(Array.isArray(values[i]) {o[k] >= values[i][0] && o[k] <= values[i][1] } else {o[k] === values[i]}))
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You have to use the ternary operator to perform a conditional in an expression, not if.

result = data.filter(o => cols.every((k, i) => 
    Array.isArray(values[i]) ? 
        o[k] >= values[i][0] && o[k] <= values[i][1] :
        o[k] === values[i]
    ));
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda