Advertisement

TrimwebsolutionsTrimwebsolutions

Problem and Solutions

Javascript remove only object from array by using filter failed in JS ?

By M.K. Verma · 3 May 2022

Javascript remove only object from array by using filter failed in JS ?

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