0

I have an array with objects in it, I'm trying to see if an object is included in it , but includes() returns false, even when it's true

my array:


let borrows = [
    { bookId: 0, userId: 0 },
    { bookId: 4, userId: 1 },
    { bookId: 1, userId: 9 },
    { bookId: 2, userId: 1 },
];

the function I'm callilng:

function returning(bookId,userId){
    if(!bookId | !userId){
        throw new Error('parameters not supplied')
    }
    else{
        if( borrows.includes({bookId:bookId,userId:userId})){
            
            borrows.splice({bookId:bookId,userId:userId});
        }
        else{
            throw new Error ('no such borrow exists')
        }
    }
        
}

calling the function:

returning(4,1)

throws error

no such borrow exists

I tried to console.log() the array and the data sent in the includes(), and it looks exactly as expected.

I ran this function separately (in the browser console) and it also returned false,

I am confident that the problem is in this line of code and would like to understand why.

I read it may be related to the address in the memory, how can I work around it without:

 found=false;
        for(let i =0; i<borrows.length & !found; i++){
            if(borrows[i].bookId==bookId & borrows[i].userId==userId)
                found=true;
        }
        if(found){
            ...
        }

Thanks

HMT
  • 21
  • 5
  • `{bookId:bookId,userId:userId}` is a newly created object. It will never be in the `borrows` array. Objects are only the same if they really are the same object, not when they happen to have the same values for their properties. – trincot Mar 16 '23 at 14:07
  • Includes won't work like that as it will look for the _exact same object_ `{} == {} // false`. You'll need to use another method like `find` or `filter` instead. – evolutionxbox Mar 16 '23 at 14:07
  • 1
    [`some()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) is the appropriate method to return a boolean, but if you are going to splice just use [`findIndex()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex) and check for valid index return. see [Get the index of the object inside an array, matching a condition](https://stackoverflow.com/questions/15997879/get-the-index-of-the-object-inside-an-array-matching-a-condition) – pilchard Mar 16 '23 at 14:14
  • Thank you for your help, pilchard. I used the findIndex() , but now how do I delete it from the array? I did: let first=[],second=[] borrows.copyWithin(first,0,place) borrows.copyWithin(second,place+1) borrows=first.concat(second) but I'm sure there is a better way – HMT Mar 18 '23 at 22:22

0 Answers0