-2

I try like this :

<script type="text/javascript">
    var clubs = [ 
        {id: 1, name : 'chelsea'},
        {id: 2, name : 'city'},
        {id: 3, name : 'liverpool'}
    ];
    var newClub = {id: 4, name: 'manchester united'}
    for(var i=0; i<clubs.length; i++) {
        if(clubs[i].id!=newClub.id) {
            clubs.push(newClub);
            break;
        }
    }
    console.log(clubs);
</script>

I want to add condition. If id of newClub object is not exist in the clubs array, then I want to add the object to the array

It works

But I ask. Is that the best way? Or is there another better way?

3
  • "It works' No, it doesn't. Commented Apr 11, 2018 at 7:41
  • @T.J. Crowder I check in the console, it works Commented Apr 11, 2018 at 7:42
  • Run it a second time, and you'll find you push the same club in again. You're pushing any time the first club in the array isn't a match for the new club. Commented Apr 11, 2018 at 7:43

3 Answers 3

6

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

It does not work, because you insert in the first loop the object. You need to check all elements and if all element does not contain the wanted id, you could add the object top the array.

Not working code, spot the index.

var clubs = [{ id: 1, name: 'chelsea' }, { id: 2, name: 'city' }, { id: 3, name: 'liverpool' }],
    newClub = { id: 4, name: 'manchester united' },
    i;
    
for (i = 0; i < clubs.length; i++) {
  if (clubs[i].id != newClub.id) {
    clubs.push(newClub);
    break;
  }
}

console.log(i, clubs);

Working code with a check if all clubs do not contain the new id.

var clubs = [{ id: 1, name: 'chelsea' }, { id: 2, name: 'city' }, { id: 3, name: 'liverpool' }],
    newClub = { id: 4, name: 'manchester united' };
    
if (!clubs.some(({ id }) => id === newClub.id)) {
    clubs.push(newClub);
}

console.log(clubs);

Comments

1

try with this

arr1.some function

var clubs = [{
    id: 1,
    name: 'chelsea'
  },
  {
    id: 2,
    name: 'city'
  },
  {
    id: 3,
    name: 'liverpool'
  }
];
var newClub = {
  id: 4,
  name: 'manchester united'
}
let found = clubs.some(r => r.id == newClub.id)
for (var i = 0; i < clubs.length; i++) {
  if (!clubs.some(r => r.id == newClub.id)) {
    clubs.push(newClub);
  }
}
console.log(clubs);

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.