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

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

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 Denunciar

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 Denunciar

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 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