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

152
Views
check if array of objects includes un object javascript

Each formation contains an array of users and I want to check if one user is part of formation's users. u: the user I want to check if they are part of formation.users. This is my code

 console.log(u)
 console.log(formation.users)
 console.log(formation.users.indexOf(u))

Which u is object and formation.users is array of objects . This is what i see in the console

{ id: 2 }

[ User { id: 2 }, User { id: 3 } ]

-1 We see the array includes the object, why do I obtain this result? Any help please.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

No, you don't see that the array includes the object, you see that the array includes an object with { id: 2 }. Unless it's the exact same object (not some other object that may or may not have the same id property as yours), it won't match:

const a = { id: 1 }
const b = { id: 1 }
const c = b

// Now there exist two objects, both with { id: 1 }.
// The first one is assigned to a, and the second
// one is assigned to both b and c. Therefore, b and c
// are equal, but a isn't equal to either of them.

console.log(a === b) // false
console.log(b === c) // true

Probably you want to check if it contains any object with a matching id instead:

console.log(formation.users.some(user => user.id === u.id))

(This is based on your question to "check if it's included" - if you actually want the index, which is what your existing code suggests that uses indexOf and not includes, then you'd have to use findIndex instead of some.)

about 4 years ago · Juan Pablo Isaza Report

0

Each object in javascript is it's own entity. So let a = {id: 1} and let b = {id: 1} in this example a and b are different objects. When you try to do the comparison match with indexOf it follows strict equality, so because they are different object it does not match them.

To achieve what you want to will need to match on one of the inner properties of user.

formation.users.findIndex((user) => user.id === u.id)
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!