1

I'm trying to add an object to an array if it's not already in the array. Seems pretty simple but not working. My array still comes back empty. Where am I making a mistake?

var members = [];
var member = { id: 123, name: "Jane Doe" };


members.find((item) => {
  if(members.length === 0 || item.id !== member.id)
    members.push(member);
})

3 Answers 3

3

I don't think it's a proper way to use find as in your code; find expects a boolean value returned and

returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

You could just pull the condition out, then you can test and push values into members:

var members = [];
var member = { id: 123, name: "Jane Doe" };

if(!members.some(item => item.id === member.id)) {
  members.push(member);
}

console.log(members);

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, it working with one correction. The condition should be item.id !== member.id because we want to make sure the member is NOT already in the array. Thank you for your help.
I lift the negation operator to the front, it's logically the same, if you use item.id !== member.id, then you might need to use every instead of some to keep the logic equivalent.
I see now. I missed that at first glance. Thanks again.
1

I'm not sure if using .find() is the best approach here. .find() would return an item from the array if the callback you pass to it returns true.

Try using something else like .includes() -

var members = [];
var member = { id: 123, name: "Jane Doe" };

console.log(members);

if(!members.includes(item => member.id === item.id) || !members.length) {
  members.push(member);
}

console.log(members);

Comments

0

You are calling members.find(...) on members which is empty []; So find will exit immediately since it doesn't have any elements.

Try initializing members to something like this:

var members = [{id:111, name:"Joe Blo"}];

then you will see two elements in members

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.