Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

80
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!