It works
No, it doesn't. :-) You're pushing the new club if the first entry isn't a match:
var clubs = [
{id: 1, name : 'chelsea'},
{id: 2, name : 'city'},
{id: 3, name : 'liverpool'}
];
function pushClub(newClub) {
for(var i=0; i<clubs.length; i++) {
if(clubs[i].id!=newClub.id) {
clubs.push(newClub);
break;
}
}
}
var newClub = {id: 4, name: 'manchester united'}
pushClub(newClub);
pushClub(newClub);
console.log(JSON.stringify(clubs));
.as-console-wrapper {
max-height: 100% !important;
}
Note that there are two id = 4 clubs.
You need to loop through the whole array before you know whether you should add the new item.
I'd probably use Array#some to see whether the item was present:
if (!clubs.some(c => c.id == newClub.id)) {
clubs.push(newClub);
}
var clubs = [
{id: 1, name : 'chelsea'},
{id: 2, name : 'city'},
{id: 3, name : 'liverpool'}
];
function pushClub(newClub) {
if (!clubs.some(c => c.id == newClub.id)) {
clubs.push(newClub);
}
}
var newClub = {id: 4, name: 'manchester united'}
pushClub(newClub);
pushClub(newClub);
console.log(JSON.stringify(clubs));
.as-console-wrapper {
max-height: 100% !important;
}
Note that there is only one id = 4 club.
I'm using an ES2015+ arrow function there, but you could use an ES5 traditional function:
if (!clubs.some(function(c) { return c.id == newClub.id; })) {
clubs.push(newClub);
}
The loop is in some, which returns true if the callback ever returns a truthy value, or false if it never does. (It also stops early when the callback returns a truthy value.)
If you wanted to update the existing club if present, I'd use Array#find instead:
var existingClub = clubs.find(c => c.id == newClub.id);
if (existingClub) {
existingClub.name = newClub.name;
} else {
clubs.push(newClub);
}