Reputation: 30388
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);
})
Upvotes: 1
Views: 65
Reputation: 3692
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);
Upvotes: 1
Reputation: 1389
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
Upvotes: 0
Reputation: 214927
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);
Upvotes: 3