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

79
Visualizações
javascript remove only object from array by using filter failed

let c = [{tenantId:1, cost:30}];
let b = c.filter(x => x.tenantId == 1);
alert(b.length);

When i create the array c with only object in it as above code, i expect the b.length is 0, but it is 1. However, when add another object into the array c and then do the same filter operation, i got the expected answer, which the b.length equals 1.(2 objects filtered 1 and left 1). Does anyone knows why it happens?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

.filter keeps elements matching the test, rather than removing them.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

If you can console.log() the whole array instead of simply the length, you will be able to see what it contains. Alternatively, you could alert(JSON.stringify(b)).

about 4 years ago · Juan Pablo Isaza Relatório

0

let c = [{tenantId:1, cost:30}];
let b = c.filter(x => x.tenantId != 1);
console.log(b.length);

You need to add x.tenantId != 1 this line of code.

about 4 years ago · Juan Pablo Isaza Relatório

0

Just switch the == to !== and you're good.

Why?:

The filter method will keep all elements that return true when passed through your condition. In your original code, you are telling filter to "Please keep all objects in this array where tenantId is equal to 1". If you want to remove these, you should tell it "Please keep all objects where tenantId doesn't equal 1"

const arr = [{ tenantId: 1, cost: 30 }];
const filtered = arr.filter(({ tenantId }) => tenantId !== 1);
console.log(filtered, `Length: ${filtered.length}`);

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