Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}`);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading