Home > Back-end >  javascript remove only object from array by using filter failed
javascript remove only object from array by using filter failed

Time:05-03

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?

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related