I have an array, clients, which I want to run array.find() on. This array contains objects, and usually looks something like this:
[ { customId: 'user1', clientId: 'TPGMNrnGtpRYtxxIAAAC' },
{ customId: 'user2', clientId: 'G80kFbp9ggAcLiDjAAAE' } ]
This is where I encounter a problem. I am trying to use find() to see if any object (or part of an object) in the array matches a certain variable, recipient, which usually contains a value like user1. the code I am using to do this is:
function checkID(recipient) {
return recipient;
}
var found = clients.find(checkID);
This always returns the first object in the array. Am I using find() wrong, or is there a better way to do this?
recipientrefers to the object, soreturn recipientwill always result in atrueresult, meaning the first iteration throughfind()will returntrueand stop. What are you trying to check? Maybe you want something more likereturn recipient.clientId === clientIdVariable, as an example.findtakes a function that receives an element from the array and returns a boolean indicating whether the element matches a condition. YourcheckIdfunction always returns the element it receives, which gets cast to a boolean, which will be true as long as the element itself isn’t falsy (false, null, 0, undefined), so it’s no surprise that this always returns the first element.